Java string to date conversion

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.
Last updated:8/10/2015 5:56:59 AM

1 Answers

Anonymous User
Anonymous User

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