1

如何在有效的 java 日期中解析以下日期字符串?我无法解析时区。

“2013-10-10 10:43:44 GMT+5”

我正在使用以下方法来解析日期。当时区类似于“GMT+05:00”但无法解析上述字符串时,它运行良好,即使我使用 z、Z、X 的不同组合

  public static Date convertStringWithTimezoneToDate(String dateString) {
        if (dateString == null) {
            return null;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzzz");
        Date convertedDate = null;
        try {
            convertedDate = dateFormat.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return convertedDate;
    }
4

1 回答 1

0

您的日期格式是非标准的。时区必须遵守文档中给出的语法:

GMTOffsetTimeZone:
         GMT Sign Hours : Minutes
 Sign: one of
         + -
 Hours:
         Digit
         Digit Digit
 Minutes:
         Digit Digit
 Digit: one of
         0 1 2 3 4 5 6 7 8 9

此代码将您的格式转换为标准格式并构造一个 Java 日期对象。

public static Date convertStringWithTimezoneToDate(String dateString) {
    if (dateString == null) {
        return null;
    }
    dateString += ":00";
    System.out.println(dateString);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    Date convertedDate = null;
    try {
        convertedDate = dateFormat.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return convertedDate;
}

PS:z模式字符串中只需要一个。

于 2014-05-18T22:13:22.250 回答