Reputation: 83
I'm trying to parse a String
into Data
, I create the DataParser, in according to date format, the code I wrote is this:
String date_s = "04-May-2017 17:28:27";
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
Date date;
try {
date = formatter.parse(date_s);
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I execute this, I got always an exception
java.text.ParseException: Unparseable date: "04-May-2017 17:28:27"
I don't understand why the data is not parsed, someone can help me?
Upvotes: 1
Views: 427
Reputation: 254
You need another constructor with a Locale
that supports MMM
(May)
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss",Locale.US)
or using standard format dd-MM-yyyy
with month digits.
(Sorry, in the meantime the answer was already posted)
Upvotes: 0
Reputation: 86389
This thread of answers would not be complete without the modern solution. These days you should no longer use Date
and SimpleDateFormat
, but switch over to the newer date and time classes:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss", Locale.ENGLISH);
LocalDateTime dateTime;
try {
dateTime = LocalDateTime.parse(date_s, formatter);
System.out.println(dateTime);
} catch (DateTimeParseException e) {
System.err.println(e);
}
This prints
2017-05-04T17:28:27
(LocalDateTime.toString()
returns ISO 8601 format) If leaving out Locale.ENGLISH
, on my computer I get
Text '04-May-2017 17:28:27' could not be parsed at index 3
Index 3 is where it say May
, so the message is somewhat helpful.
LocalDateTime
and DateTimeFormatter
were introduced in Java 8, but have also been backported to Java 6 and 7.
Upvotes: 2
Reputation: 48307
the string you want to parse is local dependent (the word May is English), so the jvm is not able to infer that may is the month of may in English
define the formatter using the constructor qith the locale.
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss",Locale.ENGLISH);
Upvotes: 0