Convert String to Date, Date to String in Java

Filed Under: Java

Sometimes we have to Convert String to Date in java program or convert Date to String in a different format for printing.

Convert String to Date

Here is a simple scenario where we will have to convert String to Date in Java. The string is one of the most widely used Object in Java. If you are working in web services or web applications with form, you get a date in the form of the String object. So in the server side, we have to convert String to a Date object.

Convert Date to String

Similarly while showing date information on any web page, we have to convert Date to String in the required format. It’s a very common process and you will see some form of date on almost all the websites.

Convert String to Date in Java

We have some specific classes in java for Date to String formatting. java.text.DateFormat is the abstract class for Date/Time formatting. java.text.SimpleDateFormat is the concrete class we use to convert String to Date and to convert Date to String in different formats.

Let’s see how to convert String to Date and convert Date to String in java program.


package com.journaldev.util;

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

/**
 * Convert String to Date in Java Example
 * Convert Date to String in Java Example
 * 
 * @author pankaj
 *
 */
public class DateUtils {
	public static void main(String[] args) {
		// initialize SimpleDateFormat object
		DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

		try {
			// Convert String to Date in java
			Date today = sdf.parse("14/11/2012");
			System.out.println("Date is : " + today.toString());

			// using locale
			sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.CHINESE);
			DateFormat sdf1 = new SimpleDateFormat("dd-MMM-yyyy", Locale.CANADA_FRENCH);

			
			today = new Date();
			System.out.println("Default Date is : " + today.toString());

			// Convert Date to String in Java
			System.out.println("CHINESE Format Date : "+sdf.format(today));
			System.out.println("CANADA_FRENCH Format Date : "+sdf1.format(today));

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

From example, it’s clear that we use parse(String str) method to convert String to Date object.

For converting Date to String, we use format(Date date) method. Note that both of these methods implementation is provided in DateFormat class and SimpleDateFormat inherits them through java inheritance.

DateFormat class supports TimeZone and Locale specific conversions also. That’s why you will see that the output of the above program varies based on locale information provided at the time of creating a SimpleDateFormat instance.

convert string to date in java, convert date to string in java

DateFormat format characters

Like java regular expression, we have to use specific characters to create the pattern to use by DateFormat class. Here is the list of all the important characters we should know:

Letter Date or Time component Example
G Era Designator AD, BC
y Year 2012, 12
M Month in year Aug, 08
w Week in year 27, 52
W week in month 2, 4
d Day in month 12, 31
D Day in year 365, 123
u Day number of week, 1=Monday 1, 7
a AM/PM marker AM, PM
H hour in day (0-23) 23
k hour in day (1-24) 22
K hour in AM/PM (0-11) 10
m minute in hour (0-59) 23
s Seconds in minute (0-59) 43
S milliseconds (0-999) 567
z General TimeZone PST, CST, GMT
Z RFC 822 TimeZone -0800
X ISO 8601 TimeZone -08, -08:00

Java Date Format String

Let’s extend our program a bit to support multiple String formats while parsing to Date. This situation can arise when you have a web page or XML field that supports multiple formats for passing date as a string.


package com.journaldev.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class StringToDateUtil {

	private List<SimpleDateFormat> sdfList;

	// set the List of Format's you want to use
	public StringToDateUtil(List<SimpleDateFormat> sdfList) throws Exception {
		if (sdfList == null)
			throw new Exception("sdfList can't be null");
		this.sdfList = sdfList;
	}

	public Date stringToDate(String str) throws Exception {
		if (str == null)
			return null;
		Date date = null;
		// parse the input String with list of SimpleDateFormats we have
		for (SimpleDateFormat sdf : sdfList) {
			try {
				date = sdf.parse(str);
			} catch (ParseException pe) {
				// do nothing, we need to try other format
			}
			// check if parsed successfully?
			if (date != null)
				break;
		}
		// return date if parsed successfully or else throw exception
		if (date != null)
			return date;
		throw new Exception("invalid format for String:" + str);
	}

	public static void main(String args[]) throws Exception {
		List<SimpleDateFormat> formatList = new ArrayList<>();
		formatList.add(new SimpleDateFormat("dd MMM yyyy"));
		formatList.add(new SimpleDateFormat("M/dd/yyyy"));
		formatList.add(new SimpleDateFormat("M/dd/yyyy hh:mm:ss a"));
		
		StringToDateUtil sdUtil = new StringToDateUtil(formatList);
		// Lets format some String to Date
		
		String[] arr = { "10 NOV 2012", "10/14/2012", "10/14/2012 10:45:30", "ABC", null };
		for (String str : arr) {
			try {
				System.out.println(str + " Date Object = " + sdUtil.stringToDate(str));
			} catch (Exception e) {
				System.out.println(str + " is not a valid date");
			}
		}
	}

}

In the above class, we are passing all the format’s of Date string that we are expecting and then stringToDate(String str) method use those to parse given String.

Here is the output of the above program.


10 NOV 2012 Date Object = Sat Nov 10 00:00:00 IST 2012
10/14/2012 Date Object = Sun Oct 14 00:00:00 IST 2012
10/14/2012 10:45:30 Date Object = Sun Oct 14 00:00:00 IST 2012
ABC is not a valid date
null Date Object = null

Note that you should create static object for a list of formats in your application rather than initializing it all the time.

You might also want to create Singleton class for this purpose.

DateFormat class is not thread-safe. So if you want thread safety, you need to create a wrapper class for SimpleDateFormat and implement synchronized format and parse methods that internally invokes DateFormat methods.

Update: Java 8 new Date Time API provides easy and standard approach for handling parsing and date formatting, you should check it out at Java 8 Date tutorial.

Comments

  1. Tarun Soni says:

    Hi i wnat date object without time zone

    { String date= “10-MAY-2016”;
    SimpleDateFormat dateFormat= new SimpleDateFormat(“dd-MMM-yyyy”);
    System.out.println(dateFormat.format(dateFormat.parse(date))); }

    op is Tue May 10 00:00:00 IST 2016 i dont want that ist part how can i do this ?

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages