What pattern should be used to parse the date stri

2019-08-24 17:27发布

While looking at this question, I discovered that both the OP's and the accepted answer's code, when run, produce a ParseException. Here is the code:

    String dateString = new java.util.Date().toString();

    System.out.println(dateString);

    SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");

    Date date = format.parse(dateString);

    System.out.println(date.toString());

After closely examining how the date string printed differs with the format provided, I still can't find why they don't match. Here is the date string printed:

Sat Aug 19 18:58:41 BST 2017

My instincts tell me that the reason why this does not work is that my locale is different - Locale.getDefualt() returns ja_JP.

1条回答
▲ chillily
2楼-- · 2019-08-24 17:49

The pattern does not matter, but the locale does. Date#toString uses Locale.US and English names for days, months and time zones, while SimpleDateFormat(String) uses your default locale (specifically: Locale.getDefault(Locale.Category.FORMAT)). If those two locales do not match, parsing may fail as the local names are not guaranteed to match.

So you should be fine with

new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);

Excerpts from JDK 8:

SimpleDateFormat:

public SimpleDateFormat(String pattern)
{
    this(pattern, Locale.getDefault(Locale.Category.FORMAT));
}

Date:

public String toString() {
    // "EEE MMM dd HH:mm:ss zzz yyyy";
    BaseCalendar.Date date = normalize();
    StringBuilder sb = new StringBuilder(28);
    int index = date.getDayOfWeek();
    if (index == BaseCalendar.SUNDAY) {
        index = 8;
    }
    convertToAbbr(sb, wtb[index]).append(' ');                        // EEE
    convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
    CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

    CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
    CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
    CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
    TimeZone zi = date.getZone();
    if (zi != null) {
        sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
    } else {
        sb.append("GMT");
    }
    sb.append(' ').append(date.getYear());  // yyyy
    return sb.toString();
}

[...]

private final static String wtb[] = {
    "am", "pm",
    "monday", "tuesday", "wednesday", "thursday", "friday",
    "saturday", "sunday",
    "january", "february", "march", "april", "may", "june",
    "july", "august", "september", "october", "november", "december",
    "gmt", "ut", "utc", "est", "edt", "cst", "cdt",
    "mst", "mdt", "pst", "pdt"
查看更多
登录 后发表回答