How to convert date in String to Date Object

11 December 2011 By admin 1,469 views One Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×

Whenever a user enters a date information, we get that as String type. There is a need to convert this String to java.util.Date Object.

Here is where, Java provides a class called SimpleDateFormat available in java.text package which allows for date formatting (date -> text) through format() method and parsing (text -> date) through parse() method.

In this tutorial, we will convert the String in a particular date format to java.util.Date object.

1. Assume the date text (got from user or by any other means) is available in String variable.

String myDateStr = "04/23/2011";

2. Create a SimpleDateFormat object by using the constructor,

public SimpleDateFormat(String pattern)

Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the default locale. Note: This constructor may not support all locales. For full coverage, use the factory methods in the DateFormat class.

Parameters:
pattern – the pattern describing the date and time format

String pattern = "MM/dd/yyyy";
SimpleDateFormat formatter = new SimpleDateFormat(pattern);

3. Now use the parse() method to convert the date in text format to Date object.

Date myDateObj = formatter.parse(myDateStr);

The parse() method throws ParseException. So either surround with try/catch block or add throws statement in the method signature.

Complete Code:

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

public class StringToDate {
	public static void main(String[] args) {
		String myDateStr = "04/23/2011";
		String pattern = "MM/dd/yyyy";
		SimpleDateFormat formatter = new SimpleDateFormat(pattern);
		Date myDateObj = null;
		try {
			myDateObj = formatter.parse(myDateStr);
			System.out.println("Date in text format: " + myDateStr);
			System.out.println("Date in java.util.Date Obj : " + myDateObj);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}

For converting Date to String refer this tutorial.

  • jitender

    where we can use this?