问题
I have the following string: dateToParse = "Fri May 16 23:59:59 BRT 2014"
, and want to parse it using DateFormat:
DateFormat dateFormat = new SimpleDateFormat(pattern, Locale.getDefault());
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/Sao_Paulo"));
cal.setTime(dateFormat.parse(dateToParse));
right now I'm trying it with pattern = "EEE MMM dd HH:mm:ss z yyyy"
, but get this exception:
java.text.ParseException: Unparseable date: "Fri May 16 23:59:59 BRT 2014" (at offset 0)
I can't figure out what's wrong with this pattern, specially at index 0... any idea what am I missing? Thanks.
[EDIT] So part of the problem was I was using Locale.getDefault(), so problably trying to parse a date in english with a dateFormat in portuguese... with the correct Locale, I'm still getting ParseException, but this time at offset 20, which means something is going wrong when parsing the timezone ('BRT', in my case)...
回答1:
its probably because of the Locale.
Try changing
Locale.getDefault()
to
Locale.ENGLISH
like this
String date_ = "Fri May 16 23:59:59 BRT 2014";
DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
Calendar date = Calendar.getInstance(TimeZone.getTimeZone("America/Sao_Paulo"));
dateFormat.setCalendar(date);
try {
date.setTime(dateFormat.parse(date_));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
回答2:
Are you sure? The code ran fine in my machine
public static void main(String[] args) throws ParseException {
String date = "Fri May 16 23:59:59 BRT 2014";
String pattern = "EEE MMM dd HH:mm:ss z yyyy";
DateFormat dateFormat = new SimpleDateFormat(pattern, Locale.getDefault());
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/Sao_Paulo"));
cal.setTime(dateFormat.parse(date));
}
回答3:
maybe this pattern works for you "EEE MMM d HH:mm:ss Z yyyy" if not take a look at his site http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Ex:
String pattern = "EEE MMM dd HH:mm:ss z yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, Locale.getDefault());
Calendar d = Calendar.getInstance();
try {
d.setTime(dateFormat.parse(String.valueOf(d)));
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
来源:https://stackoverflow.com/questions/23914287/parseexception-cant-figure-out-the-right-pattern