DateFormat
1. Introduction to DateFormat
The purpose of DateFormat is to format and parse "date/time". In fact, it is a formatting tool for Date. It can help us format Date and then convert Date into the String string we want for us to use. However, DateFormat's formatting Date has limited functionality and is not as powerful as SimpleDateFormat; but DateFormat is the parent class of SimpleDateFormat. So, we first have a comprehensive understanding of DateFormat, and then learn SimpleDateFormat.
The function of DateFormat is to format Date. It supports 4 formatting styles including FULL, LONG, MEDIUM and SHORT:
(01) DateFormat.SHORT
Completely a number, such as 12.13.52 or 3:30pm
(02) DateFormat.MEDIUM
Longer, such as Jan 12, 1952
(03) DateFormat.LONG
Longer, like January 12, 1952 or 3:30:32pm
(04) DateFormat.FULL
is fully specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.
The definition of DateFormat is as follows
public abstract class NumberFormat extends Format {}
The default constructor of DateFormat's function interface:
DateFormat()
Non-constructor:
Object clone()boolean equals(Object object)abstract StringBuffer format(Date date, StringBuffer buffer, FieldPosition field)final StringBuffer format(Object object, StringBuffer buffer, FieldPosition field)final String format(Date date)static Locale[] getAvailableLocales()Calendar getCalendar()final static DateFormat getInstance()final static DateFormat getDateInstance(int style)final static DateFormat getDateInstance(int style, Locale locale)final static DateFormat getDateTimeInstance(int style, Locale locale)final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle)final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle)final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale locale)NumberFormat getNumberFormat()TimeZone getTimeZone()int hashCode()boolean isLenient()Date parse(String string)abstract Date parse(String string, ParsePosition position)Object parseObject(String string, ParsePosition position)void setCalendar(Calendar cal)void setLenient(boolean value)void setNumberFormat(NumberFormat format)void setTimeZone(TimeZone timezone)
Note: DateFormat is an abstract class.
When we get the DateFormat instance through getInstance(), getDateInstance() and getDateTimeInstance() of DateFormat; it is actually the returned SimpleDateFormat object.
The following functions are actually the SimpleDateFormat objects returned.
final static DateFormat getInstance()final static DateFormat getTimeInstance()final static DateFormat getTimeInstance(int style)final static DateFormat getTimeInstance(int style, Locale locale)final static DateFormat getDateInstance()final static DateFormat getDateInstance(int style, Locale locale)final static DateFormat getDateTimeInstance()final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle)final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale locale)
These functions are defined in SimpleDateFormat.java as follows:
public static final int FULL = 0;public static final int LONG = 1;public static final int MEDIUM = 2;public static final int SHORT = 3;public static final int DEFAULT = MEDIUM;public final static DateFormat getInstance() { return getDateTimeInstance(SHORT, SHORT);}public final static DateFormat getTimeInstance(){ return get(DEFAULT, 0, 1, Locale.getDefault());}public final static DateFormat getTimeInstance(int style){ return get(style, 0, 1, Locale.getDefault());}public final static DateFormat getTimeInstance(int style, Locale aLocale){ return get(style, 0, 1, aLocale);}public final static DateFormat getDateInstance(){ return get(0, DEFAULT, 2, Locale.getDefault());}public final static DateFormat getDateInstance(int style){ return get(0, style, 2, Locale.getDefault());}public final static DateFormat getDateInstance(int style, Locale aLocale){ return get(0, style, 2, aLocale);}public final static DateFormat getDateTimeInstance(){ return get(DEFAULT, DEFAULT, 3, Locale.getDefault());}public final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle){ return get(timeStyle, dateStyle, 3, Locale.getDefault());}public final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale){ return get(timeStyle, dateStyle, 3, aLocale);}/** * Get the DateFormat instance, which is actually returning the SimpleDateFormat object. * * timeStyle -- The value can be "FULL" or "LONG" or "MEDIUM" or "SHORT" * dateStyle -- The value can be "FULL" or "LONG" or "MEDIUM" or "SHORT" * flags -- The value can be "1" or "2" or "3". * 1 means to get "time style" * 2 means to get "date style" * 3 means to get "time and date style" * loc -- locale object, representing "area" */private static DateFormat get(int timeStyle, int dateStyle, int flags, Locale loc) { if ((flags & 1) != 0) { if (timeStyle < 0 || timeStyle > 3) { throw new IllegalArgumentException("Illegal time style " + timeStyle); } } else { timeStyle = -1; } if ((flags & 2) != 0) { if (dateStyle < 0 || dateStyle > 3) { throw new IllegalArgumentException("Illegal date style " + dateStyle); } } else { dateStyle = -1; } try { // Check whether a provider can provide an implementation that's closer // to the requested locale than what the Java runtime itself can provide. LocaleServiceProviderPool pool = LocaleServiceProviderPool.getPool(DateFormatProvider.class); if (pool.hasProviders()) { DateFormat providersInstance = pool.getLocalizedObject( DateFormatGetter.INSTANCE, loc, timeStyle, dateStyle, flags); if (providersInstance != null) { return providersInstance; } } return new SimpleDateFormat(timeStyle, dateStyle, loc); } catch (MissingResourceException e) { return new SimpleDateFormat("M/d/yy h:mm a"); }}Through the above code, we can further realize that the function of DateFormat is to format Date; help us convert Date into the String string we need. DateFormat provides very limited functions, it can only support four formats: FULL, LONG, MEDIUM and SHORT. Moreover, when we get the DateFormat instance, it is actually the returned SimpleDateFormat object.
2. DateFormat instance
Below, we learn the commonly used APIs using DateFormat through examples.
The source code is as follows (DateFormatTest.java):
import java.util.Date;import java.util.Locale;import java.text.DateFormat;import java.text.FieldPosition;/** * API test program for DateFormat*/public class DateFormatTest { public static void main(String[] args) { // Show only "time": Call getTimeInstance() function testGetTimeInstance(); // Show only "date": Call getDateInstance() function testGetDateInstance(); // Show "date" + "time": Call getDateTimeInstance() function testGetDateTimeInstance(); // Test format() function testFormat(); } /** * Test the getTimeInstance() function of DateFormat* It has 3 overloaded forms: * (01) getTimeInstance() * (02) getTimeInstance(int style) * (03) getTimeInstance(int style, Locale locale) * * @author skywang */ private static void testGetTimeInstance() { Date date = new Date(); //Locale locale = new Locale("fr", "FR"); Locale locale = new Locale("zh", "CN"); // equivalent to DateFormat.getTimeInstance( DateFormat.MEDIUM); DateFormat short0 = DateFormat.getTimeInstance( ); // The parameters are: "Display style of time" DateFormat short1 = DateFormat.getTimeInstance( DateFormat.SHORT); DateFormat medium1 = DateFormat.getTimeInstance( DateFormat.MEDIUM); DateFormat long1 = DateFormat.getTimeInstance( DateFormat.LONG); DateFormat full1 = DateFormat.getTimeInstance( DateFormat.FULL); // The parameters are: "DateFormat display style" and "region" DateFormat short2 = DateFormat.getTimeInstance( DateFormat.SHORT, locale); DateFormat medium2 = DateFormat.getTimeInstance( DateFormat.MEDIUM, locale); DateFormat long2 = DateFormat.getTimeInstance( DateFormat.LONG, locale); DateFormat full2 = DateFormat.getTimeInstance( DateFormat.FULL, locale); System.out.println("/n----getTimeInstance ---/n" + "(1.0) Empty Param : " + short0.format(date) +"/n" + "(2.1) One Param(s) : " + short1.format(date) +"/n" + "(2.2) One Param(m) : " + medium1.format(date) +"/n" + "(2.3) One Param(l) : " + long1.format(date) +"/n" + "(2.4) One Param(f) : " + full1.format(date) +"/n" + "(3.1) One Param(s,l): " + short2.format(date) +"/n" + "(3.2) One Param(m,l): " + medium2.format(date) +"/n" + "(3.3) One Param(l,l): " + long2.format(date) +"/n" + "(3.4) One Param(f,l): " + full2.format(date) +"/n" ); } /** * Test the getDateTimeInstance() function of DateFormat* It has 3 overloaded forms: * (01) getDateInstance() * (02) getDateInstance(int style) * (03) getDateInstance(int style, Locale locale) */ public static void testGetDateTimeInstance() { Date date = new Date(); Locale locale = new Locale("zh", "CN"); // Equivalent to DateFormat.getDateTimeInstance( DateFormat.MEDIUM); DateFormat short0 = DateFormat.getDateTimeInstance( ); DateFormat short1 = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT); DateFormat medium1 = DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.MEDIUM); DateFormat long1 = DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.LONG); DateFormat full1 = DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.FULL); DateFormat short2 = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT, locale); DateFormat medium2 = DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.MEDIUM, locale); DateFormat long2 = DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.LONG, locale); DateFormat full2 = DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.FULL, locale); System.out.println("/n----getDateTimeInstance ---/n" + "(1.0) Empty Param: " + short0.format(date) +"/n" + "(2.1) One Param(s): " + short1.format(date) +"/n" + "(2.2) One Param(m) : " + medium1.format(date) +"/n" + "(2.3) One Param(l) : " + long1.format(date) +"/n" + "(2.4) One Param(f) : " + full1.format(date) +"/n" + "(3.1) One Param(s,l): " + short2.format(date) +"/n" + "(3.2) One Param(m,l): " + medium2.format(date) +"/n" + "(3.3) One Param(l,l): " + long2.format(date) +"/n" + "(3.4) One Param(f,l): " + full2.format(date) +"/n" ); } /** * Test the getDateInstance() function of DateFormat* It has 3 overloaded forms: * (01) getDateTimeInstance() * (02) getDateTimeInstance(int dateStyle, int timeStyle) * (03) getDateTimeInstance(int dateStyle, int timeStyle, Locale locale) */ public static void testGetDateInstance() { Date date = new Date(); //Locale locale = new Locale("en", "US"); Locale locale = new Locale("zh", "CN"); // equivalent to DateFormat.getDateInstance( DateFormat.MEDIUM); DateFormat short0 = DateFormat.getDateInstance( ); DateFormat short1 = DateFormat.getDateInstance( DateFormat.SHORT); DateFormat medium1 = DateFormat.getDateInstance( DateFormat.MEDIUM); DateFormat long1 = DateFormat.getDateInstance( DateFormat.LONG); DateFormat full1 = DateFormat.getDateInstance( DateFormat.FULL); DateFormat short2 = DateFormat.getDateInstance( DateFormat.SHORT, locale); DateFormat medium2 = DateFormat.getDateInstance( DateFormat.MEDIUM, locale); DateFormat long2 = DateFormat.getDateInstance( DateFormat.LONG, locale); DateFormat full2 = DateFormat.getDateInstance( DateFormat.FULL, locale); System.out.println("/n----getDateInstance ---/n" + "(1.0) Empty Param : " + short0.format(date) +"/n" + "(2.1) One Param(s) : " + short1.format(date) +"/n" + "(2.2) One Param(m) : " + medium1.format(date) +"/n" + "(2.3) One Param(l) : " + long1.format(date) +"/n" + "(2.4) One Param(f) : " + full1.format(date) +"/n" + "(3.1) One Param(s,l): " + short2.format(date) +"/n" + "(3.2) One Param(m,l): " + medium2.format(date) +"/n" + "(3.3) One Param(l,l): " + long2.format(date) +"/n" + "(3.4) One Param(f,l): " + full2.format(date) +"/n" ); } /** * Test DateFormat format() function*/ public static void testFormat() { Date date = new Date(); StringBuffer sb = new StringBuffer(); FieldPosition field = new FieldPosition(DateFormat.YEAR_FIELD); DateFormat format = DateFormat.getDateTimeInstance(); sb = format.format(date, sb, field); System.out.println("/ntestFormat"); System.out.printf("sb=%s/n", sb); }} Running results:
---getTimeInstance ---(1.0) Empty Param : 4:54:22 PM(2.1) One Param(s) : 4:54 PM(2.2) One Param(m) : 4:54:22 PM(2.3) One Param(l) : 4:54:22 PM CST(2.4) One Param(f) : 4:54:22 PM CST(3.1) One Param(s,l): 4:54:22 PM CST(3.1) One Param(s,l): 4:54 (3.2) One Param(m,l): 16:54:22 (3.3) One Param(l,l): 4:54:22 pm (3.4) One Param(f,l): 4:54:22 pm CST---getDateInstance ---(1.0) Empty Param: Jan 23, 2014(2.1) One Param(s): 1/23/14(2.2) One Param(m): Jan 23, 2014(2.3) One Param(l): January 23, 2014(2.4) One Param(f): Thursday, January 23, 2014(3.1) One Param(s,l): 14-1-23(3.2) One Param(m,l): 2014-1-23(3.3) One Param(l,l): January 23, 2014(3.4) One Param(f,l): Thursday, January 23, 2014---getDateTimeInstance ----(1.0) Empty Param: Jan 23, 2014 4:54:23 PM(2.1) One Param(s): 1/23/14 4:54 PM(2.2) One Param(m): Jan 23, 2014 4:54:23 PM(2.3) One Param(l): January 23, 2014 4:54:23 PM CST(2.4) One Param(f): Thursday, January 23, 2014 4:54:23 PM CST(3.1) One Param(s,l): 14-1-23 4:54:23 PM CST(3.1) One Param(s,l): 2014-1-23 16:54:23(3.3) One Param(l,l): 04:54:23(3.4) One Param(f,l): Thursday, January 23, 2014 04:54:23 PM CST(3.1) One Param(s,l): Thursday, January 23, 2014 04:54:23 PM CSTtestFormatsb=Jan 23, 2014 4:54:23 PM
OK. So far, the learning of DateFormat has ended. Next, we start to learn SimpleDateFormat, which is what you need to understand when formatting Date.
SimpleDateFormat
1. Introduction to SimpleDateFormat
SimpleDateFormat is a tool for formatting Date and parsing date strings. Its most commonly used is to format the Date in the specified format, and then we use the strings we can format the Date.
More strictly speaking, SimpleDateFormat is a specific class that formats and parses dates in a locale-related way. It allows formatting (date->text), parsing (text->date), and normalization.
SimpleDateFormat constructor:
Constructor
SimpleDateFormat()SimpleDateFormat(String pattern)SimpleDateFormat(String template, DateFormatSymbols value)SimpleDateFormat(String template, Locale locale)
Non-constructor
void applyLocalizedPattern(String template)void applyPattern(String template)Object clone()boolean equals(Object object)StringBuffer format(Date date, StringBuffer buffer, FieldPosition fieldPosition)AttributedCharacterIterator formatToCharacterIterator(Object object)Date get2DigitYearStart()DateFormatSymbols getDateFormatSymbols()int hashCode()Date parse(String string, ParsePosition position)void set2DigitYearStart(Date date)void setDateFormatSymbols(DateFormatSymbols value)String toLocalizedPattern()String toPattern()
SimpleDateFormat Simple Demonstration:
// Create a new date object, the time is 2013-09-19Date date = new Date(113,8,19); // Create a new "SimpleDateFormat object", and set the "format mode" of sdf SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// Format date with sdf and return the string. String str = sdf.format(date); 2. SimpleDateFormat related format description
2.1 Date and time mode
The date and time format is specified by the date and time pattern string. In date and time pattern strings, unquoted letters 'A' to 'Z' and 'a' to 'z' are interpreted as pattern letters to represent date or time string elements. Text can be enclosed in single quotes (') to avoid explanation. "''" means single quotes. All other characters are not interpreted; they are simply copied to the output string when formatted, or matched to the input string when parsed.
The following pattern letters are defined (all other characters 'A' to 'Z' and 'a' to 'z' are preserved):
| letter | Date or time element | express | Example |
| G | Era logo | Text | AD |
| y | Year | Year | 1996; 96 |
| M | Mid-year month | Month | July; Jul; 07 |
| w | Weeks in the year | Number | 27 |
| W | Weeks in the month | Number | 2 |
| D | Days in the year | Number | 189 |
| d | Days in the month | Number | 10 |
| F | Week of the month | Number | 2 |
| E | Days of the week | Text | Tuesday; Tue |
| a | Am/pm tag | Text | PM |
| H | Hours in a day (0-23) | Number | 0 |
| k | Hours in a day (1-24) | Number | twenty four |
| K | Number of hours in am/pm (0-11) | Number | 0 |
| h | Number of hours in am/pm (1-12) | Number | 12 |
| m | Minutes in hours | Number | 30 |
| s | Number of seconds in minutes | Number | 55 |
| S | Number of milliseconds | Number | 978 |
| z | Time zone | General time zone | Pacific Standard Time; PST; GMT-08:00 |
| Z | Time zone | RFC 822 time zone | -0800 |
| Date and time mode | result |
| "yyyy.MM.dd G 'at' HH:mm:ss z" | 2001.07.04 AD at 12:08:56 PDT |
| "EEE, MMM d, ''yy" | Wed, Jul 4, '01 |
| "h:mm a" | 12:08 PM |
| "hh 'o''clock' a, zzzz" | 12 o'clock PM, Pacific Daylight Time |
| "K:mm a, z" | 0:08 PM, PDT |
| "yyyyyy.MMMMMM.dd GGG hh:mm aaa" | 02001.July.04 AD 12:08 PM |
| "EEE, d MMM yyyy HH:mm:ss Z" | Wed, 4 Jul 2001 12:08:56 -0700 |
| "yyMMddHHmmssZ" | 010704120856-0700 |
| "yyyy-MM-dd'T'HH:mm:ss.SSSZ" | 2001-07-04T12:08:56.235-0700 |
import java.util.Date;import java.util.Locale;import java.util.Calendar;import java.text.DateFormat;import java.text.SimpleDateFormat;/** * API test program of SimpleDateFormat* * @author skywang * @email [email protected] */public class SimpleDateFormatTest { public static void main(String[] args) { // Get date/time through SimpleDateFormat: There are multiple formats to testSimpleDateFormats(); // Get date/time with DateFormat superTest() ; } /** * Get date/time with SimpleDateFormat. There are many formats to choose */ private static void testSimpleDateFormats() { String[] formats = new String[] { "HH:mm", // 14:22 "h:mm a", // 2:22 pm "HH:mm z", // 14:22 +0800 "HH:mm zzzz", // 14:22 China Standard Time "HH:mm:ss", // 14:22 "yyyy-MM-dd", // 2013-09-19 "yyyy-MM-dd HH:mm", // 2013-09-19 14:22 "yyyy-MM-dd HH:mm:ss", // 2013-09-19 14:22:30 "yyyy-MM-dd HH:mm:ss zzzz", // 2013-09-19 14:22:30 "yyyyy-MM-dd HH:mm:ss.SSSZ", // 2013-09-19 14:22:30 "yyyy-MM-dd HH:mm:ss.SSSZ", // 2013-09-19 14:22:30 "yyyy-MM-dd HH:mm:ss.SSSZ", // 2013-09-19T14:22:30.000+0800 "yyyyy.MM.dd G 'at' HH:mm:ss z", // 2013.09.19 AD at 14:22:30 CST "K:mm a", // 2:22 pm, CST "EEE, MMM d, ''yyy", // Thursday, September 19, '13 "hh 'o''clock' a, zzzz", // 02 o'clock pm, CST "yyyyyy.MMMM.dd GGG hh:mm aaa", // 02013. September 19 AD at 02:22 pm"EEE, d MMM yyyy HH:mm:ss Z", // Thursday, 19 September 2013 14:22:30 +0800 "yyMMddHHmmssZ", // 130919142230+0800 "yyyy-MM-dd'T'HH:mm:ss.SSSZ", // 2013-09-19T14:22:30.000+0800 "EEEE 'DATE('yyyy-MM-dd')' 'TIME('HH:mm:ss')' zzzz", // Thursday, 2013-09-19 14:22:30 CST}; // Date date = (new Date(0)); // date is 1970-01-01 07:00:00 //Date date = Calendar.getInstance().getTime(); // date is the current time Date date = new Date(113, 8, 19, 14, 22, 30); // date is 2013-09-19 14:22:30 for (String format : formats) { SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.SIMPLIFIED_CHINESE); //SimpleDateFormat sdf = new SimpleDateFormat(format); System.out.format("%30s %s/n", format, sdf.format(date)); } } /** * Get date/time through DateFormat*/ private static void superTest() { // Create a new date object, the time is 2013-09-19 14:22:30 // (01) year = "'Target Year' - 1900", // (02) month. 0 is January, 1 is February, and so on. // (03) Day. Number between 1-31 Date mDate = new Date(113, 8, 19, 14, 22, 30); Locale locale = new Locale("zh", "CN"); // 14:22:30 String time = DateFormat.getTimeInstance( DateFormat.MEDIUM, Locale.SIMPLIFIED_CHINESE).format(mDate); // 2013-09-19 String date = DateFormat.getDateInstance( DateFormat.MEDIUM, Locale.SIMPLIFIED_CHINESE).format(mDate); // 2013-09-19 14:22:30 String datetime = DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.SIMPLIFIED_CHINESE).format(mDate); System.out.printf("/ntime=%s/ndate=%s/ndatetime=%s/ndatetime=%s/n",time,date,datetime); }}
Running results:
HH:mm 14:22 h:mm a 2:22 pm HH:mm z 14:22 CST HH:mm Z 14:22 +0800 HH:mm zzzz 14:22 CST HH:mm:ss 14:22:30 yyyy-MM-dd 2013-09-19 yyyy-MM-dd HH:mm 2013-09-19 14:22:30 yyyy-MM-dd HH:mm:ss 2013-09-19 14:22:30 yyyy-MM-dd HH:mm:ss zzzz 2013-09-19 14:22:30 yyyy-MM-dd HH:mm:ss zzzz 2013-09-19 14:22:30 yyyy-MM-dd HH:mm:ss zzzz 2013-09-19 14:22:30 yyyy-MM-dd HH:mm:ss zzzz 2013-09-19 14:22:30 yeEEE yyyy-MM-dd HH:mm:ss zzzz Thursday 2013-09-19 14:22:30 CST K:mm a 2:22:30.000+0800 yyyy-MM-dd'T'HH:mm:ss.SSSZ 2013-09-19T14:22:30.000+0800 yyyyy.MM.dd G 'at' HH:mm:ss z 2013.09.19 AD at 14:22:30 CST K:mm a 2:22 pm EEE, MMM d, ''yy Thursday, September 19, '13 hh 'o''clock' a, zzzz 02 o'clock pm, yyyyyy.MMMMMM.dd GGG hh:mm aaa 02013. September 19 02:22 pm EEE, d MMM yyyy HH:mm:ss Z Thursday, 19 September 2013 14:22:30 +0800 yyMMddHHmmssZ 130919142230+0800 yyyy-MM-dd'T'HH:mm:ss.SSSZ 2013-09-19T14:22:30.000+0800EEEE 'DATE('yyyy-MM-dd')' 'TIME('HH:mm:ss')' zzzz Thursday DATE(2013-09-19) TIME(14:22:30) China Standard Time=14:22:30date=2013-9-19datetime=2013-9-19 14:22:30