DateFormat and SimpleDateFormat Examples

Version 1.1 of Java introduced the java.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));
    }
}



Figure 1. Using default DateFormat objects to format a Date object.

When you run this class, you will see output that looks something like that shown in Figure 2.



> 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



Figure 2. Output from example in Figure 1

Default 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 + "\"");
        }
    }
}



Figure 3. Using default DateFormat objects to parse a String

The result is shown in Figure 4. Note that since the string version of the date did not contain timezone or seconds, the timezone is set to the default timezone (EST, in this case) and the seconds are set to zero.



> java DateFormatExample2
Original string: Nov 4, 2003 8:14 PM
Parsed date    : Tue Nov 04 20:14:00 EST 2003



Figure 4. Parsing a date string

The 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);
        }
    }
}



Figure 5. Example of parsing dates entered on the command line

Figure 6 shows an example of running this class and entering several date strings. (Text entered is shown in italics.)



> 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: 



Figure 6. Parsing a variety of date strings

Note that the default parser is somewhat flexible. It recognizes a long version of the month name (“November” instead of “Nov”), but does not recognize the two dates shown in red, both of which are missing AM or PM. Furthermore, it produces possibly unexpected results when the time “20:14 PM” is entered: The parsed date is 8:14 the next morning.

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.



SymbolMeaningTypeExample
GEraText“GG” -> “AD”
yYearNumber“yy” -> “03”
“yyyy” -> “2003”
MMonthText or Number“M” -> “7”
“M” -> “12”
“MM” -> “07”
“MMM” -> “Jul”
“MMMM” -> “December”
dDay in monthNumber“d” -> “3”
“dd” -> “03”
hHour (1-12, AM/PM)Number“h” -> “3”
“hh” -> “03”
HHour (0-23)Number“H” -> “15”
“HH” -> “15”
kHour (1-24)Number“k” -> “3”
“kk” -> “03”
KHour (0-11 AM/PM)Number“K” -> “15”
“KK” -> “15”
mMinuteNumber“m” -> “7”
“m” -> “15”
“mm” -> “15”
sSecondNumber“s” -> “15”
“ss” -> “15”
SMillisecond (0-999)Number“SSS” -> “007”
EDay in weekText“EEE” -> “Tue”
“EEEE” -> “Tuesday”
DDay in year (1-365 or 1-364)Number“D” -> “65”
“DDD” -> “065”
FDay of week in month (1-5)Number“F” -> “1”
wWeek in year (1-53)Number“w” -> “7”
WWeek in month (1-5)Number“W” -> “3”
aAM/PMText“a” -> “AM”
“aa” -> “AM”
zTime zoneText“z” -> “EST”
“zzz” -> “EST”
“zzzz” -> “Eastern Standard Time”
Excape for textDelimiter“‘hour’ h” -> “hour 9”
Single quoteLiteral“ss”SSS” -> “45’876”



Figure 7. Syntax elements for SimpleDateFormat

Note that you will generally never want to use single-digit minutes, seconds, or milliseconds, even though these are supported by 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



Figure 8. A parser for Date.toString() output