0

I'm trying to parse a date from string but i get a wrong date result and dont understand why :/

String dateStr = "September 6, 2013 - 10:48";
SimpleDateFormat parser = new SimpleDateFormat("MMMM dd, YYYY - HH:mm", Locale.US);
Date date = parser.parse(dateStr);

When I look date result (in debugger) i see : Sun Dec 30 10:48:00 CET 2012 Can someone tell me where I'm wrong please ?

Jo44
  • 46
  • 8
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 06 '20 at 18:53

1 Answers1

3
        String dateStr = "September 6, 2013 - 10:48";
        SimpleDateFormat parser = new SimpleDateFormat(
                "MMMM dd, yyyy - hh:mm", Locale.US);
        Date date = parser.parse(dateStr);
        System.out.println(date);

Use yyyy and not YYYY

Also don't use Date but use LocalDate and LocalDateTime.

Here is how you would do it using LocalDateTime

        String dateStr = "September 6, 2013 - 10:48";
        DateTimeFormatter format = DateTimeFormatter.ofPattern(
                "MMMM d, y - HH:mm",Locale.US);
        LocalDateTime date = LocalDateTime.parse(dateStr,format);
        System.out.println(date.format(format));

Note the HH is for 24 hour time since you didn't include an AM or PM in your date string.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • Thx a lot, your answer fixed my problem ! Can you explain why I should avoid using Date ? In my case, I only use it for this parse, and convert it to Calendar for my object just after – Jo44 Apr 06 '20 at 17:56
  • 2
    It is deprecated. LocalDate, LocalDateTime and other related classes and methods have substantially more sophisticated and useful methods. Check out [java.time](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/time/package-summary.html) for more info. – WJS Apr 06 '20 at 18:46
  • 2
    `Calendar` too is poorly designed and long outdated. Don’t use it either. [Why do we need a new date and time library?](https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html) See also [Still using java.util.Date? Don’t!](https://programminghints.com/2017/05/still-using-java-util-date-dont/) – Ole V.V. Apr 06 '20 at 19:00