Home > DeveloperSection > Forums > Java string to date conversion
Mark Devid
Mark Devid

Total Post:102

Posted on    August-10-2015 1:04 AM

 Java Java  DateTime  String 

 1 Reply(s)
 719  View(s)
Rate this:
Can somebody recommend the best way to convert a string in the format 'January 2, 2010' to a date in java? Ultimately, I want to break out the month, the day, and the year as integers so that I can use:

Date date = new Date();
date.setlong currentTime = date.getTime();
to convert the date into time.

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    August-10-2015 5:56 AM

String string = "January 2, 2010";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010

If you happen to be on Java 8 already, then use DateTimeFormatter (also here, click the link to see all predefined formatters and available format patterns; the tutorial is available here). This new API is inspired by JodaTime.
String string = "January 2, 2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2010-01-02

Don't want to miss updates? Please click the below button!

Follow MindStick