问题
I'm having the date in this pattern EEEEE MMMMM yyyy HH:mm:ss.SSSZ, I would like to convert this to yyyy-MM-dd format in java, I tried below approach but I'm getting this exception java.text.ParseException: Unparseable date:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "Sun Oct 01 00:00:00 EDT 2017";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Can someone please help me to resolve this?
Thanks.
回答1:
From java-8 you can use the ZonedDateTime
with pattern of your input date which is EEE MMM dd HH:mm:ss zzz yyyy
String dateInString = "Sun Oct 01 00:00:00 EDT 2017";
ZonedDateTime time = ZonedDateTime.parse(dateInString,DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"));
System.out.println(time.toLocalDate()); //2017-10-01
By default LocalDate
is without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.
回答2:
You've defined your formatter as the concept 'date, month, year', and then you try to ask it to parse a string that isn't in this format at all. You need to make a formatter that can format Sun Oct 01 00:00:00 EDT 2017
, and dd-MMM-yyyy
obviously isn't it. The javadoc of SimpleDateFormat will tell you what combination of letters you need to use.
Once you've got that, it's easy: parse with this new formatter, then call .format
with your old one (the dd-MMM-yyyy
one).
回答3:
You can't use the same formatter for both parsing and formatting. See this answer: https://stackoverflow.com/a/999191
回答4:
You double-create the DateFormat one parse and once to format
DateFormat dfParse = new SimpleDateFormat("EEEEE MMMMM yyyy HH:mm:ss.SSSZ");
DateFormat dfFormat = new SimpleDateFormat("yyyy-MM-dd");
dfFormat.format(dfParse.parse("Sun Oct 01 00:00:00 EDT 2017"))
来源:https://stackoverflow.com/questions/58313283/how-to-parse-date-string-eee-mmm-dd-to-yyyy-mm-dd-in-java