ivanhjc ivanhjc - 9 days ago 6
Java Question

How do you parse date String in the form "Nov 17, 2016 7:26:57 PM" into Date?

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()
?

Answer

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
Comments