SimpleDateFormat解析失去时区 [英] SimpleDateFormat parse loses timezone
问题描述
代码:
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: Output: Note that 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 : Output : slightly dubious, but I want only the date to be consistent
这篇关于SimpleDateFormat解析失去时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
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
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()
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? 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