SimpleDateFormat解析失去时区 [英] SimpleDateFormat parse loses timezone

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

问题描述

代码:

  SimpleDateFormat sdf = new SimpleDateFormat(yyyy.MM.dd HH:mm:ss z); 
sdf.setTimeZone(TimeZone.getTimeZone(GMT));
System.out.println(new Date());
try {
String d = sdf.format(new Date());
System.out.println(d);
System.out.println(sdf.parse(d));
} catch(Exception e){
e.printStackTrace(); //更改catch语句的主体使用File |设置|文件模板
}

输出:

  Thu Aug 08 17:26:32 GMT + 08:00 2013 
2013.08.08 09:26:32 GMT
Thu Aug 08 17:26:32 GMT +08:00 2013

请注意, format() Date 正确格式化为GMT,但 parse()丢失了GMT详细信息。我知道我可以使用 substring()并解决这个问题,但这种现象的原因是什么?



这是一个重复的问题,没有任何答案。 / p>

编辑:让我以另一种方式提出问题,检索Date对象的方法是什么,以便始终在GMT?

所有我需要的是:

 code> SimpleDateFormat sdf = new SimpleDateFormat(yyyy.MM.dd HH:mm:ss); 
sdf.setTimeZone(TimeZone.getTimeZone(GMT));

SimpleDateFormat sdfLocal = new SimpleDateFormat(yyyy.MM.dd HH:mm:ss);


try {
String d = sdf.format(new Date());
System.out.println(d);
System.out.println(sdfLocal.parse(d));
} catch(Exception e){
e.printStackTrace(); //更改catch语句的主体使用File |设置|文件模板
}

输出:稍微怀疑,但我只希望日期一致



  2013.08.08 11:01:08 
Thu Aug 08 11:01:08 GMT + 08:00 2013


Code:

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    System.out.println(new Date());
    try {
        String d = sdf.format(new Date());
        System.out.println(d);
        System.out.println(sdf.parse(d));
    } catch (Exception e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

Output:

Thu Aug 08 17:26:32 GMT+08:00 2013
2013.08.08 09:26:32 GMT
Thu Aug 08 17:26:32 GMT+08:00 2013

Note that format() formats the Date correctly to GMT, but parse() lost the GMT details. I know I can use substring() and work around this, but what is the reason underlying this phenomenon?

Here is a duplicate question which doesn't have any answers.

Edit: Let me put the question in another way, what is the way to retrieve a Date object so that its always in GMT?

解决方案

All I needed was this :

       SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

        SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");


        try {
            String d = sdf.format(new Date());
            System.out.println(d);
            System.out.println(sdfLocal.parse(d));
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

Output : slightly dubious, but I want only the date to be consistent

2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013

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

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