The SimpleDateFormat:
SimpleDateFormat pdf = new SimpleDateFormat("MM dd yyyy hh:mm:ss:SSSaa");
The exception thrown by pdf.parse("Mar 30 2010 5:27:40:140PM");
:
java.text.ParseException: Unparseable date: "Mar 30 2010 5:27:40:140PM"
Any ideas?
Edit: thanks for the fast answers. You were all correct, I just missed that one key sentence in the SimpleDateFormat docs - I should probably call it a day.
First, three-char months are to be represented by MMM
. Second, one-two digit hours are to be represented by h
. Third, Mar
seems to be English, you'll need to supply a Locale.ENGLISH
, else it won't work properly in machines with a different default locale.
The following works:
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy h:mm:ss:SSSa", Locale.ENGLISH);
System.out.println(sdf.parse("Mar 30 2010 5:27:40:140PM"));
Result (I'm at GMT-4 w/o DST):
Tue Mar 30 17:27:40 BOT 2010
Also see the java.text.SimpleDateFormat
javadoc .
Why you called it pdf
is beyond me, so I renamed it sdf
;)
From SimpleDateFormat javadocs :
Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.
Try to use pattern like "MMM dd yyyy"
MM stands for numeric month. Use MMM.
I am providing the modern answer. The other answers are correct, but the SimpleDateFormat
class that you used is notoriously troublesome and long outdated. Instead I am using java.time, the modern and superior Java date and time API.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"MMM d uuuu h:mm:ss:SSSa", Locale.ROOT);
String dateTimeString = "Mar 30 2010 5:27:40:140PM";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println(dateTime);
Output:
2010-03-30T17:27:40.140
Link: Oracle tutorial: Date Time explaining how to use java.time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.