String

Java String to Date Example

Java gives us the capability to convert String to Date. This can be done through DateFormat and SimpleDateFormat classes, where the last class is a subclass of the first one. It is worth to mention that DateFormat is not thread-safe, so it is recommended to create different instances for each thread.

In this example we will show you how to parse from String to date format.

 
 
 
 

1. Some date and time patterns

First of all we are going to present the most common date and time pattern-letters that are used in order to format a date.

  • y: defines the year
  • M: defines the month in year
  • d: defines the day in month as a number
  • D: represents the day in year as a number
  • E: represents the name of the day in week
  • a: marks am/pm in hour
  • H: defines the hour in day (0-23)
  • h: defines the hour in am/pm (0-11)
  • m: represents the minutes in hour
  • s: represents the seconds in minute
  • z: defines the timezone

Notice that the letter (capital or small) does matter for the date format, for instance M and m have different definitions. You can see all the possible patterns in the java doc of SimpleDateFormat.

2. Syntax of String to Date conversion

In order to convert a String to Date we should make two basic steps:

  1. Create an instance of DateFormat or SimpleDateFormat class and if you want, specify a date format.
  2. Call parse() operation of the above instance, by defining the particular string.

parse() method has two syntax formats:

  • public Date parse(String source): converts the source string to a Date.
  • public abstract Date parse(String source, ParsePosition pos): it also converts the given string to Date but by starting the conversion from the pos index of the string.

parse function throws ParseException if the given string is not convertible, as well as NullPointerException when the specified string is null.

3. Example of String to Date conversion

Create a java file with the name StringToDateClass and paste the following code.

StringToDateClass.java:

package com.javacodegeeks.basics.stringtodate;

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

public class StringToDateClass {

	public static void main(String[] args) {
		String dateString1 = "05-Jun-2014";
		String dateString2 = "Thu 05/06/2014, 4 pm";
		String dateString3 = "2014 05:12:16 EDT";
		Date date = null;
		
		ParsePosition pos = new ParsePosition(4);
		// use of locale
	    DateFormat format1 = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
	    // use of am/pm metric
	    DateFormat format2 = new SimpleDateFormat("dd/MM/yyyy, hh a");
	    // use of hour and timezone
	    DateFormat format3 = new SimpleDateFormat("yyyy HH:mm:ss zzz");
	    // MEDIUM format: "MMM dd, yyyy"
	    DateFormat format4 = DateFormat.getDateInstance(DateFormat.MEDIUM);
	    
	    try {
			date = format1.parse(dateString1);
			System.out.println("Date of dateString1 = " + date);
			
			// the parsing starts from the specified (pos) index
			date = format2.parse(dateString2, pos);
			System.out.println("Date of dateString2 = " + date);
			
			date = format3.parse(dateString3);
			System.out.println("Date of dateString3 = " + date);
			
			date = format4.parse("Jun 05, 2014");
			System.out.println("Date with DateFormat = " + date);
			
			// throws exception
			date = format2.parse(dateString2);

		} catch (ParseException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}

	}

}

Now let’s explain the code above. We create three different instances of SimpleDateFormat by setting different patterns, as we explained before. Especially the format1 instance uses the format symbols of a specified locale. The different patterns indicate the format of the expecting string. For instance dd-MMM-yyyy represents a format with two chars for date, three chars for month and four characters for year, separated by the char -. In addition we get an instance of DateFormat by calling getDateInstance() method, where DateFormat.MEDIUM declares the format style, as you can see in the code above.

As we mentioned before, for String to Date conversion parse() method is called. If the format of the string can not be parsed and it is not similar to the pattern we set in the DateFormat instance, a ParseException is thrown. Please observe the parsing date in format2. We defined a ParsePosition in order to remove a portion of the string and to adjust it to the desirable pattern, otherwise an exception will be thrown.

Now have a look at the output of the execution. Notice that for dateString1 and dateString3 the hour and the date have their default values respectively, because we didn’t define them in the pattern. Also observe the result of dateString3. Although we defined the EDT (Eastern Daylight Time) as timezone, it has changed to the default one – EST (East European Time) – and the hour has transformed suitably. After that, notice the string style in format4. This maps to the DateFormat.MEDIUM that we defined earlier. Finally, have a look at the timezone at the most results. The timezone is set to EEST (East European Summer Time) because the month is June, which belongs to the summer time zone.

Output:

Date of dateString1 = Thu Jun 05 00:00:00 EEST 2014
Date of dateString2 = Thu Jun 05 16:00:00 EEST 2014
Date of dateString3 = Wed Jan 01 11:12:16 EET 2014
Date with DateFormat = Thu Jun 05 00:00:00 EEST 2014
java.text.ParseException: Unparseable date: "Thu 05/06/2014, 4 pm"
	at java.text.DateFormat.parse(Unknown Source)
	at com.javacodegeeks.basics.stringtodate.StringToDateClass.main(StringToDateClass.java:43)

All the above refer to Java 7. There is a brand new Date and Time API in Java 8.

Download the source code

This was an example of String to Date in Java. Download the source code of this example: StringToDateExample.zip

Katerina Zamani

Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button