Timezone parsing issue in Java

2019-08-11 05:46发布

How do i parse the following date string in a valid java date? I am having trouble parsing the timezone.

"2013-10-10 10:43:44 GMT+5"

I am using the following method for parsing the date. It works well when the timezone is like "GMT+05:00" but fails to parse the above string even if i use different combinations of 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;
    }

1条回答
欢心
2楼-- · 2019-08-11 06:38

Your date format is non-standard. The time zone must respect the syntax given in the documentation:

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

This code the transform your format into a standard one and construct a Java date object.

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;
}

P.S.: Only one z is needed in the pattern string.

查看更多
登录 后发表回答