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(); //To change body of catch statement use File | Settings | File Templates.

}

输出:

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()并解决此问题,但是造成这种现象的原因是什么?

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

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

回答:

我需要的是:

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.

}

输出:有点可疑,但我只希望日期保持一致

2013.08.08 11:01:08

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

以上是 SimpleDateFormat解析会丢失时区 的全部内容, 来源链接: utcz.com/qa/400139.html

回到顶部