JAVA STRING TO DATE CONVERSION

Mark Devid

Total Post:102

Points:714
Posted by  Mark Devid
 785  View(s)
Ratings:
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.setMonth()..
date.setYear()..
date.setDay()..
date.setlong currentTime = date.getTime();
to convert the date into time.
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Java string to date conversion

    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!