0

I tried the following pattern with new SimpleDateFormat(pattern).parse("Nov 17, 2016 7:26:57 PM") but none of them work:

MMM d, yyyy h:m:s a
MMM dd, yyyy HH:mm:ss a
MMM dd, yyyy h:m:s a

The only way I can parse this string successfully is to use new Date("Nov 17, 2016 7:26:57 PM") but this call is obsolete. It is said to be replaced by DateFormat.parse() according to the API documentation but actually it failed to parse the same string when I call DateFormat.getDateTimeInstance().parse("Nov 17, 2016 7:26:57 PM"). So how should I parse this string correctly other than using new Date()?

Joseph Tesfaye
  • 814
  • 14
  • 26

2 Answers2

3

You need to:

  • Make sure the pattern is right
  • Specify the right locale

In this case, you want an English locale for English month names:

SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy h:mm:ss a", Locale.ENGLISH);

Note that this pattern isn't any of the ones you specified:

  • We need d because presumably you'd get "Nov 5" rather than "Nov 05"
  • We need h because you're getting a 12-hour hour, with only a single digit for values under 10
  • We need mm and ss because you'll get double digits for minutes and seconds
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I've tested that all three patterns can parse correctly after I specify the locale... – Joseph Tesfaye Nov 25 '16 at 12:48
  • @ivanhjc: They will all parse invalid data though, e.g. "23:00:00 AM", "7:5:6PM". The pattern I've provided is a much better one. It's definitely worth paying very close attention to this sort of thing. – Jon Skeet Nov 25 '16 at 12:53
-1

code:

public void testDate() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy h:mm:ss a");
        Date d1 = sdf.parse("Nov 17, 2016 7:26:57 PM");
        System.out.println(d1);
        return;
    }

output:

Thu Nov 17 19:26:57 CET 2016
Tchopane
  • 175
  • 8