解析后Java SimpleDateFormat错误的时区 [英] Java SimpleDateFormat Wrong Timezone after parsing

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

问题描述

为什么当我输入带有 GMT 时区的日期字符串时,SimpleDateFormat 会解析它并输出 EET 时区?

Why when i give input date string with GMT timezone, SimpleDateFormat parses it and outputs EET timezone?

public static String DATE_FORMAT="dd MMM yyyy hh:mm:ss z";
public static String CURRENT_DATE_STRING ="31 October 2011 11:19:56 GMT";
...
SimpleDateFormat simpleDateFormat =  new SimpleDateFormat(DATE_FORMAT, Locale.US);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(simpleDateFormat.parseObject(CURRENT_DATE_STRING));

输出为:2011 年 10 月 31 日星期一 13:19:56 EET而不是格林威治标准时间 2011 年 10 月 31 日星期一 13:19:56

And output is: Mon Oct 31 13:19:56 EET 2011 rather than Mon Oct 31 13:19:56 GMT 2011

推荐答案

您正在打印 Date.toString() 的结果.Date 没有任何时区概念——它只是自 UTC Unix 纪元以来的毫秒数.Date.toString() 始终使用系统默认时区.

You're printing out the result of Date.toString(). A Date doesn't have any concept of a timezone - it's just the number of milliseconds since the UTC Unix epoch. Date.toString() always uses the system default time zone.

请注意,您不应该期待Mon Oct 31 13:19:56 GMT 2011",因为您指定的时间指定 GMT 小时为 11,而不是 13.

Note that you shouldn't be expecting "Mon Oct 31 13:19:56 GMT 2011" given that you've given a time which specifies a GMT hour of 11, not 13.

如果要使用特定时区进行打印,则应使用另一个DateFormat 进行打印,而不是使用Date.toString().(Date.toString() 不断造成这样的混乱;这真的很不幸.)

If you want to use a specific time zone for printing, you should use another DateFormat for the printing, rather than using Date.toString(). (Date.toString() keeps causing confusion like this; it's really unfortunate.)

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

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