Saturday, September 24, 2011

How to convert String to Date in Java - SimpleDateFormat Example

SimpleDateFormat in Java can be used to convert String to Date in Java. java.text.SimpleDateFormat is an implementation of DateFormat which defines a date pattern and can convert a particular String which follows that pattern into Date in Java.This is the second part of the article on java.util.Date and String in Java. In the first part we have seen How to convert Date to String in Java. SimpleDateFormat accepts a String in any date format e.g. yyyyMMdd is a date pattern and  20110924 is a String in that format. Now you want to create a java.util.Date object from this String. In this Java tutorial we will see list steps to convert String to Date in Java and then we will see different examples of SimpleDateFormat with different date patterns e.g. ddMMyy or dd-MM-yyyy. Though converting String to Date is quite easy using SimpleDateFormat, but you need to remember that SimpleDateFormat is not thread-safe, which means you can not share same instance of SimpleDateFormat between multiple threads. Avoid storing SimpleDateFormat in static variable and if you want to safely share or reuse SimpleDateFormat, you need to make it thread-safe. One way is to use ThreadLocal variable in Java to make SimpleDateFormat thread-safe, as shown in this example.

Steps to Convert String into Date

How to convert String to Date in Java program with SimpleDateFormat exampleConverting String to date is rather common scenario because you may get date in a String format from any file or xml document. SimpleDateFormat in Java also support time information e.g. HH for hour , mm for minutes and SS for seconds.

Here are steps we need to use for conversion in Java:

1) Create a SimpleDateFormat object with a date pattern e.g. dd-MM-yyyy. here d denotes day of month, M is for month of year and yyyy is year in four digit e.g. 2012. Java documentation of SimpleDateFormat has complete list of date and time pattern specified.

2) Call parse() method of SimpleDateFormat and cast the result into Date object and you are done. parse() method of SimpleDateFormat throws ParseException so you need to either throw it or you can provide handling of this exception. Let’s see some SimpleDateFormat Example of converting string to date in Java to get hold of concept.       

SimpleDateFormat Example in Java


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


/**
 * Java program to convert String to Date in Java. This example
 * use SimpleDateFormat for String to Date conversion, you can also
 * use JODA date and time API for that.
 *
 * @author Javin
 */

public class StringToDateExample{
   
   
public static void main(String args[]) throws ParseException{
       
        DateFormat formatter =
null;
        Date convertedDate =
null;
       
       
// Creating SimpleDateFormat with yyyyMMdd format e.g."20110914"
        String yyyyMMdd =
"20110914";
        formatter =
new SimpleDateFormat("yyyyMMdd");
        convertedDate =
(Date) formatter.parse(yyyyMMdd);
        System.
out.println("Date from yyyyMMdd String in Java : " + convertedDate);

       
//convert string to date with ddMMyyyy format example "14092011"
        String ddMMyyyy =
"14092011";
        formatter =
new SimpleDateFormat("ddMMyyyy");
        convertedDate =
(Date) formatter.parse(ddMMyyyy);
        System.
out.println("Date from ddMMyyyy String in Java : " + convertedDate);

       
//String to Date conversion in Java with dd-MM-yyyy format e.g. "14-09-2011"
        String dd_MM_YY =
"14-09-2011";
        formatter =
new SimpleDateFormat("dd-MM-yyyy");
        convertedDate =
(Date) formatter.parse(dd_MM_YY);
        System.
out.println("Date from dd-MM-yyyy String in Java : " + convertedDate);

       
// dd/MM/yyyy date format for example "14/09/2011"
        String stringDateFormat =
"14/09/2011";
        formatter =
new SimpleDateFormat("dd/MM/yyyy");
        convertedDate =
(Date) formatter.parse(stringDateFormat);
        System.
out.println("Date from dd/MM/yyyy String in Java : " + convertedDate);

       
//parsing string into date with dd-MMM-yy format e.g. "14-Sep-11"
       
//MMMM denotes three letter month String e.g. Sep
        String ddMMMyy =
"14-Sep-11";
        formatter =
new SimpleDateFormat("dd-MMM-yy");
        convertedDate =
(Date) formatter.parse(ddMMMyy);
        System.
out.println("Date from dd-MMM-yy String in Java : " + convertedDate);

       
//convert string to Date of dd-MMMM-yy format e.g. "14-September-11"
       
//MMMM denotes full month String e.g. September
        String dMMMMyy =
"14-September-11";
        formatter =
new SimpleDateFormat("dd-MMMM-yy");
        convertedDate =
(Date) formatter.parse(dMMMMyy);
        System.
out.println("Date from dd-MMMM-yy String in Java : " + convertedDate);
       
       
//SimpleDateFormat also allows to include time information e.g. dd-MM-yyyy:HH:mm:SS
        String date =
"15-09-2011:23:30:45";
        formatter =
new SimpleDateFormat("dd-MM-yyyy:HH:mm:SS");
        convertedDate =
(Date) formatter.parse(date);
        System.
out.println("Date from dd-MM-yyyy:HH:mm:SS String in Java : " 
                            + convertedDate);
   
}
}

Output:
Date from yyyyMMdd String in Java : Wed Sep
14 00:00:00 PST 2011
Date from ddMMyyyy String in Java : Wed Sep
14 00:00:00 PST 2011
Date from dd-MM-yyyy String in Java : Wed Sep
14 00:00:00 PST 2011
Date from dd/MM/yyyy String in Java : Wed Sep
14 00:00:00 PST 2011
Date from dd-MMM-yy String in Java : Wed Sep
14 00:00:00 PST 2011
Date from dd-MMMM-yy String in Java : Wed Sep
14 00:00:00 PST 2011
Date from dd-MM-yyyy:HH:mm:SS String in Java : Thu Sep
15 23:30:00 PST 2011

You can check the java doc of DateFormat for all the symbols it supports and what is meaning for that but here I am listing some common points which is worth remembering while working with SimpleDateFormat for conversion.

1) Confusion between “m” and “M”, small case “m” represent minutes while “M” represent Month Also “d” represent date in month while “D” represent Day of week. This is most common cause of error while converting String to date and back date to string. In shot ddMMyy is not equal to DDmmyy.

2) SimpleDateFormat is not thread-safe. They are not synchronized so its better you create separate SimpleDateFormat for each thread to avoid any race condition while parsing.

Java is very rich in terms of date time support and it also provides convenient way to convert string to date which is very handy while working in java application.


Related Java tutorials

8 comments :

Jirka Pinkas said...

Nice. Recently I stumbled upon this library: http://www.pojava.org/ Using this library you can easily handle different input date formats.

Or you can also use Joda time.

These other libraries are thread safe (unlike SimpleDateFormat).

Also in future Java, there will be a complete revamp of SimpleDateFormat (unfortunately I don't know if it will be Java 8 or some other more distant Java).

Javin @ polymorphism in java said...

Thanks Jirka for this update, yes SimpleDateFormat needs a revamp at least on thread-safety issue, it doesn't make sense to have separate formatter for separate thread in my opinion.

Anonymous said...

Great Java SimpleDateFormat tutorial. I have read some of your java article and want to thank you for good work. I most like the last part of your article where you have pointed out subtle details on String to Date conversion

Tom said...

Great Article, I was getting lost with dates until I read it.

I ran your example and found a few problems.
Could you make a few corrections to your sample code. In each sample you have a new string but parse yyyyMMdd from the first example.

Also you have the correct format in the comment before each example but then use a different format for the SimpleDateFormat.

Tom said...

Here is my attempt:

DateFormat formatter;
Date convertedDate;

// yyyyMMdd format e.g."20110914"
String yyyyMMdd = "20110114";
formatter = new SimpleDateFormat("yyyyMMdd");
convertedDate = (Date) formatter.parse(yyyyMMdd);
System.out.println(convertedDate+" Test A");


//convert string to date with ddMMyyyy format example "14092011"
String ddMMyyyy = "14022011";
formatter = new SimpleDateFormat("ddMMyyyy");
convertedDate = (Date) formatter.parse(ddMMyyyy);
System.out.println(convertedDate+" Test B");


//string into date in java with dd-MM-yyyy format e.g. "14-09-2011"
String dd_MM_YY = "14-03-2011";
formatter = new SimpleDateFormat("dd-MM-yyyy");
convertedDate = (Date) formatter.parse(dd_MM_YY);
System.out.println(convertedDate+" Test C");


// dd/MM/yyyy format for example "14/09/2011"
String stringDateFormat = "14/04/2011";
formatter = new SimpleDateFormat("dd/MM/yyyy");
convertedDate = (Date) formatter.parse(stringDateFormat);
System.out.println(convertedDate+" Test D");


//parsing string into date with dd-MMM-yy format e.g. "14-Sep-11"
String dMMMyy = "14-May-11";
formatter = new SimpleDateFormat("dd-MMM-yy");
convertedDate = (Date) formatter.parse(dMMMyy);
System.out.println(convertedDate+" Test E");


//convert string to date of dd-MMMM-yy format e.g. "14-September-11"
String dMMMMyy = "14-June-11";
formatter = new SimpleDateFormat("dd-MMMM-yy");
convertedDate = (Date) formatter.parse(dMMMMyy);
System.out.println(convertedDate+" Test F");




Anonymous said...

Just a word of caution for all those using SimpleDateFormat, SimpleDateFormat is not thread-safe and either use it as ThreadLocal see this link or use local copy. Never use static instance of SimpleDateFormat

Sohan said...

String inputStr = "05/01/2012 10:51:47 AM PDT";
String inputFmt = "MM/dd/yyyy hh:mm:ss a z";
SimpleDateFormat dfLong = new SimpleDateFormat(inputFmt);;
Date localModifiedDate = dfLong.parse(inputStr);
System.out.println(localModifiedDate);

Giving me Unparsable date exception

Zeeshan Akhter said...

Date Conversion from String to sql Date in Java:

String startDate="01-02-2013";
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date date = sdf1.parse(startDate)
java.sql.Date sqlStartDate = new Date(date.getTime());

Post a Comment