Which template should I use to parse the date string returned toString from java.util.Date?

If I look at the question , I find that both the OP and the accepted response code are created at startup 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 carefully examining how the printed date string differs from the format, I still cannot find out why they do not match. Below is the date string:

Sat Aug 19 18:58:41 BST 2017

My instincts tell me that the reason this doesn't work is because my language is different - it Locale.getDefualt()returns ja_JP.

0
source share
1 answer

, . Date#toString Locale.US , , SimpleDateFormat(String) ( : Locale.getDefault(Locale.Category.FORMAT)). , , .

,

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

JDK 8:

SimpleDateFormat:

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

:

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"
+1

Source: https://habr.com/ru/post/1684038/


All Articles