DateFormat and SimpleDateFormat Examples
Version 1.1 of Java introduced thejava.text
package, which included utility classes for parsing and formatting
numbers and dates, along with utility classes for building other kinds
of parsers.Default date formats
The
java.text.DateFormat
class, and its concrete subclass java.text.SimpleDateFormat
, provide a convenient way to convert strings with date and/or time info to and from java.util.Date
objects. Figure 1 shows an example of using default DateFormat
objects to format a date in a variety of ways:
import java.text.DateFormat; import java.util.Date; public class DateFormatExample1 { public static void main(String[] args) { // Make a new Date object. It will be initialized to the current time. Date now = new Date(); // See what toString() returns System.out.println(" 1. " + now.toString()); // Next, try the default DateFormat System.out.println(" 2. " + DateFormat.getInstance().format(now)); // And the default time and date-time DateFormats System.out.println(" 3. " + DateFormat.getTimeInstance().format(now)); System.out.println(" 4. " + DateFormat.getDateTimeInstance().format(now)); // Next, try the short, medium and long variants of the // default time format System.out.println(" 5. " + DateFormat.getTimeInstance(DateFormat.SHORT).format(now)); System.out.println(" 6. " + DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now)); System.out.println(" 7. " + DateFormat.getTimeInstance(DateFormat.LONG).format(now)); // For the default date-time format, the length of both the // date and time elements can be specified. Here are some examples: System.out.println(" 8. " + DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT).format(now)); System.out.println(" 9. " + DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.SHORT).format(now)); System.out.println("10. " + DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.LONG).format(now)); } }
DateFormat
objects to format a Date
object.> java DateFormatExample1 1. Tue Nov 04 20:14:11 EST 2003 2. 11/4/03 8:14 PM 3. 8:14:11 PM 4. Nov 4, 2003 8:14:11 PM 5. 8:14 PM 6. 8:14:11 PM 7. 8:14:11 PM EST 8. 11/4/03 8:14 PM 9. Nov 4, 2003 8:14 PM 10. November 4, 2003 8:14:11 PM EST
DateFormat
objects retrieved from the static getInstance()
, getTimeInstance()
, and getDateTimeInstance()
methods can also be used for parsing String
objects to produce Date
objects. Figure 3 shows a simple example of this.import java.text.DateFormat; import java.text.ParseException; import java.util.Date; public class DateFormatExample2 { public static void main(String[] args) { // Make a String that has a date in it, with MEDIUM date format // and SHORT time format. String dateString = "Nov 4, 2003 8:14 PM"; // Get the default MEDIUM/SHORT DateFormat DateFormat format = DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.SHORT); // Parse the date try { Date date = format.parse(dateString); System.out.println("Original string: " + dateString); System.out.println("Parsed date : " + date.toString()); } catch(ParseException pe) { System.out.println("ERROR: could not parse date in string \"" + dateString + "\""); } } }
DateFormat
objects to parse a String
> java DateFormatExample2 Original string: Nov 4, 2003 8:14 PM Parsed date : Tue Nov 04 20:14:00 EST 2003
parse
method throws an exception if a date matching
the format cannot be parsed. In the code shown in Figure 3, the string
matches the format exactly. To see what happens when a bad string is
encountered, the class in Figure 5 reads and attempts to parse input
until a blank line (or a Control-D) is entered.import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; public class DateFormatExample3 { public static void main(String[] args) { // Get the default MEDIUM/SHORT DateFormat DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT); // Read and parse input, stopping on a blank input line BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("ENTER DATE STRING: "); String dateString = reader.readLine(); while ((dateString != null) && (dateString.length() > 0)) { // Parse the date try { Date date = format.parse(dateString); System.out.println("Original string: " + dateString); System.out.println("Parsed date : " + date.toString()); System.out.println(); // Skip a line } catch(ParseException pe) { System.out.println( "ERROR: could not parse date in string \"" + dateString + "\""); } // Read another string System.out.print("ENTER DATE STRING: "); dateString = reader.readLine(); } } catch(IOException ioe) { System.out.println("I/O Exception: " + ioe); } } }
> java DateFormatExample3 ENTER DATE STRING: Nov 4, 2003 8:14 PM Original string: Nov 4, 2003 8:14 PM Parsed date : Tue Nov 04 20:14:00 EST 2003 ENTER DATE STRING: Nov 4, 2003 8:14 ERROR: could not parse date in string "Nov 4, 2003 8:14 " ENTER DATE STRING: Nov 4, 2003 8:14 AM Original string: Nov 4, 2003 8:14 AM Parsed date : Tue Nov 04 08:14:00 EST 2003 ENTER DATE STRING: November 4, 2003 8:14 AM Original string: November 4, 2003 8:14 AM Parsed date : Tue Nov 04 08:14:00 EST 2003 ENTER DATE STRING: Nov 4, 2003 20:14 PM Original string: Nov 4, 2003 20:14 PM Parsed date : Wed Nov 05 08:14:00 EST 2003 ENTER DATE STRING: Nov 4, 2003 20:14 ERROR: could not parse date in string "Nov 4, 2003 20:14" ENTER DATE STRING:
DateFormat
actually gives you a small amount of control over leniency in parsing. The default DateFormat
instances are lenient by default, but invoking format.setLenient(false);
in the example in Figure 5 would cause the “20:14 PM” example (in
Figure 6) to fail, though it will still accept “November” or “Nov”.Using SimpleDateFormat for custom date formatting and parsing
The default
DateFormat
instances returned by the static methods in the DateFormat
class may be sufficient for many purposes, but clearly do not cover all
possible valid or useful formats for dates. For example, notice that in
Figure 2, none of the DateFormat
-generated strings (numbers 2 – 9) match the format of the output of the Date
class’s toString()
method. This means that you cannot use the default DateFormat
instances to parse the output of toString()
, something that might be useful for things like parsing log data.The
SimpleDateFormat
lets you build custom formats.
Dates are constructed with a string that specifies a pattern for the
dates to be formatted and/or parsed. From the SimpleDateFormat
JavaDocs, the characters in Figure 7 can be used in date formats. Where
appropriate, 4 or more of the character will be interpreted to mean
that the long format of the element should be used, while fewer than 4
mean that a short format should be used.Symbol | Meaning | Type | Example |
G | Era | Text | “GG” -> “AD” |
y | Year | Number | “yy” -> “03″ “yyyy” -> “2003″ |
M | Month | Text or Number | “M” -> “7″ “M” -> “12″ “MM” -> “07″ “MMM” -> “Jul” “MMMM” -> “December” |
d | Day in month | Number | “d” -> “3″ “dd” -> “03″ |
h | Hour (1-12, AM/PM) | Number | “h” -> “3″ “hh” -> “03″ |
H | Hour (0-23) | Number | “H” -> “15″ “HH” -> “15″ |
k | Hour (1-24) | Number | “k” -> “3″ “kk” -> “03″ |
K | Hour (0-11 AM/PM) | Number | “K” -> “15″ “KK” -> “15″ |
m | Minute | Number | “m” -> “7″ “m” -> “15″ “mm” -> “15″ |
s | Second | Number | “s” -> “15″ “ss” -> “15″ |
S | Millisecond (0-999) | Number | “SSS” -> “007″ |
E | Day in week | Text | “EEE” -> “Tue” “EEEE” -> “Tuesday” |
D | Day in year (1-365 or 1-364) | Number | “D” -> “65″ “DDD” -> “065″ |
F | Day of week in month (1-5) | Number | “F” -> “1″ |
w | Week in year (1-53) | Number | “w” -> “7″ |
W | Week in month (1-5) | Number | “W” -> “3″ |
a | AM/PM | Text | “a” -> “AM” “aa” -> “AM” |
z | Time zone | Text | “z” -> “EST” “zzz” -> “EST” “zzzz” -> “Eastern Standard Time” |
‘ | Excape for text | Delimiter | “‘hour’ h” -> “hour 9″ |
” | Single quote | Literal | “ss”SSS” -> “45’876″ |
SimpleDateFormat
SimpleDateFormat
(“m”, “s”, “S”).Using the syntax from Figure 7, we can now make a
SimpleDateFormat
that can read the output of Date.toString()
. Figure 8 shows an example this:import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.Date; public class DateFormatExample4 { public static void main(String[] args) { // Make a new Date object. It will be initialized to the // current time. Date now = new Date(); // Print the result of toString() String dateString = now.toString(); System.out.println(" 1. " + dateString); // Make a SimpleDateFormat for toString()'s output. This // has short (text) date, a space, short (text) month, a space, // 2-digit date, a space, hour (0-23), minute, second, a space, // short timezone, a final space, and a long year. SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); // See if we can parse the output of Date.toString() try { Date parsed = format.parse(dateString); System.out.println(" 2. " + parsed.toString()); } catch(ParseException pe) { System.out.println("ERROR: Cannot parse \"" + dateString + "\""); } // Print the result of formatting the now Date to see if the result // is the same as the output of toString() System.out.println(" 3. " + format.format(now)); } }The output shows three identical strings:
> java DateFormatExample4 1. Tue Nov 04 21:53:43 EST 2003 2. Tue Nov 04 21:53:43 EST 2003 3. Tue Nov 04 21:53:43 EST 2003
Date.toString()
output