Convert String to Date Using SimpleDateFormat

Most of programmers is familiar with following task: converting a string into a date. It's a common task that we often encounter in our job as a programmer. It's becomes fundamental skill in Java (or other programming language you work with) to work with a string to represent a date, and then convert it into a Date object.

Before Java 8, the Java date and time mechanism was provided by the old APIs of java.util.Date, java.util.Calendar, and java.util.TimeZone classes which until this article is out, a lot of us still need to working with it, especially in enterprise environment which slower to adapt new version of Java.

In this article, we will learn on how to convert a String to java.util.Date using class java.text.SimpleDateFormat, which is a subclass of DateFormat. DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date → text), parsing (text → date), and normalization.. The date is represented as a Date object or as the milliseconds since January 1, 1970, 00:00:00 GMT.

Date and Time Patterns

Date and time formats are specified by date and time pattern strings. Refer to table below for some of the common date and time patterns used in SimpleDateFormat.

Letter  Date or Time Component Presentation  Examples
yYear Year1996; 96
MMonth in year (context sensitive) MonthJuly; Jul; 07 
dDay in month Number10
EDay name in week TextTuesday; Tue 
aAm/pm marker TextPM
HHour in day (0-23) Number0
hHour in am/pm (1-12) Number12
mMinute in hour Number30
sSecond in minute Number55
SMillisecond Number978

And some that we might not use that often:

Letter  Date or Time Component Presentation  Examples
GEra designator TextAD
YWeek year Year2009; 09
LMonth in year (standalone form) MonthJuly; Jul; 07
wWeek in year Number27
WWeek in month Number2
DDay in year Number189
FDay of week in month Number2
uDay number of week (1 = Monday, ..., 7 = Sunday) Number1
kHour in day (1-24) Number24
KHour in am/pm (0-11) Number0
zTime zone General time zonePacific Standard Time; PST; GMT-08:00
ZTime zone RFC 822 time zone  -0800
XTime zone ISO 8601 time zone-08; -0800; -08:00

Pattern Examples

Here are a few Java SimpleDateFormat date pattern examples. Current date in my laptop is 25 June 2019, 1 AM, Singapore Time:

Date and Time Pattern Result
"dd/MM/yy"25/06/19
"dd MMM yyyy"25 Jun 2019
"yyyy-MM-dd"2019-06-25
"dd-MM-yyyy h:mm a"25-06-2019 1:11 AM
"dd-MM-yyyy hh:mm a, zzzz"25-06-2019 01:11 AM, Singapore Time
"dd-MM-yyyy HH:mm:ss"25-06-2019 01:11:28
"yyyy-MM-dd HH:mm:ss.SSS"2019-06-25 01:11:28.954
"yyyy-MM-dd HH:mm:ss.SSSZ"2019-06-25 01:11:28.954+0800
"EEEE, dd MMMM yyyy HH:mm:ss.SSSZ" Tuesday, 25 June 2019 01:11:28.954+0800 
"yyMMddHHmmssSSS"190625011128954

Creating a SimpleDateFormat

You can create a SimpleDateFormat instance like following example:

String pattern = "dd MMM yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    

The pattern parameter passed to the SimpleDateFormat constructor is the pattern specified in Date and Time Patterns above. Another way to create SimpleDateFormat is to initiate SimpleDateFormat without parameter (default constructor) like:

SimpleDateFormat sdf = new SimpleDateFormat();
System.out.println(sdf.format(date));
System.out.println(sdf.toPattern());
                    

It will constructs a SimpleDateFormat using the default pattern and date format symbols for the default FORMAT locale. Result from above example:

25/6/19 1:11 AM
d/M/yy h:mm a

Format Date to String

You can format dates using its format() method.

The Date instance passed is a java.util.Date instance. Let see following example:

Date date = new Date();
System.out.println(new SimpleDateFormat("dd-MM-yyyy").format(date));
                    

The output will be:

25-06-2019

Parse String to Date

You can parse a String into a Date instance using the parse() method

Check following example:

String strDate = "9 Apr 1980";
try {            
    Date date = new SimpleDateFormat("d MMM yyyy").parse(strDate);
    System.out.println(date);  
} catch (ParseException e) {
    System.out.println("ParseException occured: " + e.getMessage());
}
                    

And the result (Date instance toString) is:

Wed Apr 09 00:00:00 SGT 1980

Let's check more parsing example in following code:

SimpleDateFormatExample1.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample1 {

    static void printDate(Date date) {
        System.out.println(date);
    }
    
    public static void main(String[] args) {
        try { 
            printDate(new SimpleDateFormat("dd/MM/yy").parse("28/06/19"));
            printDate(new SimpleDateFormat("dd MMM yyyy").parse("28 Jun 2019"));
            printDate(new SimpleDateFormat("E, dd MMMM yyyy").parse("Fri, 28 June 2019"));
            printDate(new SimpleDateFormat("EEEE, dd MMMM yyyy HH:mm a").parse("Friday, 28 June 2019 02:20 AM"));
            printDate(new SimpleDateFormat("dd-MM-yyyy HH:mm:ssZ").parse("28-06-2019 02:30:05+0800"));
        } catch (ParseException e) {
            System.out.println("ParseException occured: " + e.getMessage());
        }
    }
}
                    

Once above code is executed, we get following result (please keep in mind, all results actually in Date and printed):

Fri Jun 28 00:00:00 SGT 2019
Fri Jun 28 00:00:00 SGT 2019
Fri Jun 28 00:00:00 SGT 2019
Fri Jun 28 02:20:00 SGT 2019
Fri Jun 28 02:30:05 SGT 2019

Time zone Format Example

Following example is to show how to work with Time zone format. There are three different presentation: General time zone, RFC 822 time zone, and ISO 8601 time zone

SimpleDateFormatExample2.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample2 {

    static void printDate(Date date) {
        System.out.println(date);
    }
    
    public static void main(String[] args) {
        SimpleDateFormat formatter = new SimpleDateFormat("d-MM-yyyy HH:mm:ssZ");
        String strDate = "28-06-2019 02:40:10+0800";

        try {
            Date date = formatter.parse(strDate);
            
            SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a, z");
            SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a, zzzz");
            SimpleDateFormat sdf3 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss aZ");
            SimpleDateFormat sdf4 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss aX");
            SimpleDateFormat sdf5 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss aXX");
            SimpleDateFormat sdf6 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss aXXX");
            
            System.out.println(sdf1.format(date));
            System.out.println(sdf2.format(date));
            System.out.println(sdf3.format(date));
            System.out.println(sdf4.format(date));
            System.out.println(sdf5.format(date));
            System.out.println(sdf6.format(date));
            
            System.out.println("\n--- SimpleDateFormat parse ---");
            printDate(sdf1.parse("28-06-2019 02:40:10 AM, SGT"));
            printDate(sdf2.parse("28-06-2019 02:40:10 AM, Singapore Time"));
            printDate(sdf3.parse("28-06-2019 02:40:10 AM+0800"));
            printDate(sdf4.parse("28-06-2019 02:40:10 AM+08"));
            printDate(sdf5.parse("28-06-2019 02:40:10 AM+0800"));
            printDate(sdf6.parse("28-06-2019 02:40:10 AM+08:00"));
        } catch (ParseException e) {
            System.out.println("ParseException occured: " + e.getMessage());
        }
    }
}
                    

And the result are:

28-06-2019 02:40:10 AM, SGT
28-06-2019 02:40:10 AM, Singapore Time
28-06-2019 02:40:10 AM+0800
28-06-2019 02:40:10 AM+08
28-06-2019 02:40:10 AM+0800
28-06-2019 02:40:10 AM+08:00
--- SimpleDateFormat parse ---
Fri Jun 28 02:40:10 SGT 2019
Fri Jun 28 02:40:10 SGT 2019
Fri Jun 28 02:40:10 SGT 2019
Fri Jun 28 02:40:10 SGT 2019
Fri Jun 28 02:40:10 SGT 2019
Fri Jun 28 02:40:10 SGT 2019

Conclusion

The SimpleDateFormat class is used to both parse and format dates according to specified Date and Time Patterns. Use parse(...) method to convert from String to Date, use format(...) method to convert from Date into String.

If you are already using Java 8 (and above), please look at DateTimeFormatter.