Converting a String into a Date in Java

This tutorial shows how to convert a java.lang.String into a java.util.Date. We can convert a String into a Date using the parse() method of the DateFormat and SimpleDateFormat classes.

// from java.lang.String into java.util.Date
String dateString = "06-Dec-1989";
Date parsed = new SimpleDateFormat("dd-MMM-yyyy").parse(dateString);

// from java.util.Date into java.lang.String
Date date = new Date();
String formatted = new SimpleDateFormat("dd-MMM-yyyy").format(date)

Convert String = 27-10-2016 to Date

String dateString = "27-10-2016";
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date date = df.parse(dateString);
System.out.println(date);
System.out.println(df.format(date));

Output:

Thu Oct 27 00:00:00 CEST 2016
27-10-2016

Convert String = 27/10/2016 to Date

String dateString = "27/10/2016";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date = df.parse(dateString);
System.out.println(date);
System.out.println(df.format(date));

Output:

Thu Oct 27 00:00:00 CEST 2016
27/10/2016

Convert String = 27 Oct, 2016 to Date

String dateString = "27 Oct, 2016";
DateFormat df = new SimpleDateFormat("d MMM, yyyy");
Date date = df.parse(dateString);
System.out.println(date);
System.out.println(df.format(date));

Output:

Thu Oct 27 00:00:00 CEST 2016
27 Oct, 2016

Convert String = Thu, Oct 27 2016 to Date

String dateString = "Thu, Oct 27 2016";
DateFormat df = new SimpleDateFormat("E, MMM dd yyyy");
Date date = df.parse(dateString);
System.out.println(date);
System.out.println(df.format(date));

Output:

Thu Oct 27 00:00:00 CEST 2016
Thu, Oct 27 2016

Convert String = Thursday, Oct 27, 2016 12:45:13 PM to Date

String dateString = "Thursday, Oct 27, 2016 12:45:13 PM";
DateFormat df = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
Date date = df.parse(dateString);
System.out.println(date);
System.out.println(df.format(date));

Output:

Thu Oct 27 12:45:13 CEST 2016
Thursday, Oct 27, 2016 12:45:13 PM

References

You may also like...