Java SimpleDateFormat 时区解析 [英] Java SimpleDateFormat timezone parsing
问题描述
我很好奇 Java 的 SimpleDateFormat 如何根据设置的时区决定何时增加/减少传入的时间.
I'm curious how Java's SimpleDateFormat decides when to increment/decrement the passed in time based on the timezone it's set to.
假设我有一个日期 06/04/2013.然后我将时区设置为离我很远的时区(我在 GMT-5).假设我使用 GMT+8.
Let's say I have a date 06/04/2013. I then set the timezone to one far away from me(I'm in GMT-5). Let's say I use GMT+8.
我打电话
SimpleDateFormat df = new SimpleDateFormat( "M/d/yy" );
df.setTimeZone( TimeZone.getTimeZone( "GMT+8" ) );
df.parse( endDate ) // this returns 06/**03**/2013 //endDate is just a String
它返回 06/03/2013.为什么它会递减它?
It returns 06/03/2013. Why does it decrement it?
基本上我想问的是,如果我将日期设置为 GMT+8,Java 用来将我的日期回退到 6/3 的参考点是什么.有一些逻辑说嘿我不在当前时区所以让我们改变它.但是由于我传入了一个字符串,所以我看不到它可能在哪里.
Basically I'm asking what is the reference point that Java uses to knock back my date to 6/3 if I set it to GMT+8. There's some logic that says hey I'm not on this current timezone so let's change it. But since I'm passing in a String I don't see where it could be.
我假设默认情况下,如果我不在字符串中提供时区,它将默认为 GMT.
I assume by default if I don't provide a Timezone in the string it will default to GMT.
推荐答案
您处于 GMT-5,并且您正在解析表示 GMT+8 时区中某个时刻的字符串.
You're in GMT-5, and you're parsing a string representing a moment in the GMT+8 time zone.
所以,日期 06/04/2013
实际上是 06/04/2013 00:00 GMT+8
.要获得格林威治标准时间的日期,您必须减去 8 小时:06/03/2013 16:00 GMT
.要获得 GMT-5 的日期,您必须再减去 5 个小时:06/03/2013 11:00 GMT-5
.
So, the date 06/04/2013
is in fact 06/04/2013 00:00 GMT+8
. To get the date at GMT, you have to subtract 8 hours: 06/03/2013 16:00 GMT
. And to get the date at GMT-5, you have to subtract another 5 hours: 06/03/2013 11:00 GMT-5
.
所有这些字符串都是同一时刻的不同表示.
All these strings are different representations of the same moment.
这篇关于Java SimpleDateFormat 时区解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!