Java SimpleDateFormat timezone parsing

2019-06-28 03:40发布

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.

标签: java timezone
1条回答
淡お忘
2楼-- · 2019-06-28 04:22

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.

查看更多
登录 后发表回答