简体   繁体   English

Java SimpleDateFormat时区解析

[英]Java SimpleDateFormat timezone parsing

I'm curious how Java's SimpleDateFormat decides when to increment/decrement the passed in time based on the timezone it's set to. 我很好奇Java的SimpleDateFormat如何根据设置的时区确定何时增加/减少传递的时间。

Let's say I have a date 06/04/2013. 假设我有个约会06/04/2013。 I then set the timezone to one far away from me(I'm in GMT-5). 然后,我将时区设置为离我较远的时区(我在GMT-5中)。 Let's say I use GMT+8. 假设我使用GMT + 8。

I call 我打电话

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

It returns 06/03/2013. 它返回2013年6月3日。 Why does it decrement it? 为什么要递减呢?

Edit: 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. 编辑:基本上,我想问的是,如果我将日期设置为GMT + 8,Java会将日期降低为6/3的参考点是什么。 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. 但是由于我要传递一个字符串,所以我看不到它在哪里。

I assume by default if I don't provide a Timezone in the string it will default to GMT. 我假设默认情况下,如果我未在字符串中提供时区,则默认为GMT。

You're in GMT-5, and you're parsing a string representing a moment in the GMT+8 time zone. 您正在使用GMT-5,并且正在解析表示GMT + 8时区中某个时刻的字符串。

So, the date 06/04/2013 is in fact 06/04/2013 00:00 GMT+8 . 因此,日期06/04/2013实际上是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 . 要获取格林尼治标准时间的日期,您必须减去8小时: 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 . 而要在GMT-5上获取日期,您必须再减去5个小时: 06/03/2013 11:00 GMT-5

All these strings are different representations of the same moment. 所有这些字符串是同一时刻的不同表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM