Timezone parsing issue in Java

放肆的年华 提交于 2019-12-11 11:22:30

问题


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:


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.



来源:https://stackoverflow.com/questions/19288687/timezone-parsing-issue-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!