Java SimpleDateFormat timezone parsing

喜欢而已 提交于 2019-12-23 13:29:28

问题


I'm curious how Java's SimpleDateFormat decides when to increment/decrement the passed in time based on the timezone it's set to.

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.

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. 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. 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.


回答1:


You're in GMT-5, and you're parsing a string representing a moment in the GMT+8 time zone.

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.



来源:https://stackoverflow.com/questions/17581112/java-simpledateformat-timezone-parsing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!