Java中的时区解析问题 [英] Timezone parsing issue in Java

查看:117
本文介绍了Java中的时区解析问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我正在使用以下方法来解析日期。当时区类似于GMT + 05:00时,即使我使用z,Z,X的不同组合,也不能解析上述字符串,它的效果很好

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


推荐答案

标准。时区必须遵守文档中给出的语法


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日期对象。

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

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

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

这篇关于Java中的时区解析问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆