4

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I thought he tried GMT-5 and it showed as the 4th, and then he tried GMT+8 and it showed up as the 3rd.
So you're saying that by default SimpleDateFormat assumes I want the date in GMT and not the timezone I pass in?
No. I precisely said that by setting the timezone of the date format to GMT+8, you're making it parse 06/04/2013 as 06/04/2013 GMT+8, which is the same moment as 06/03/2013 16:00 GMT, which is the same moment as 06/03/2013 11:00 GMT-5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.