TimeZone with Calendar confusing results

前端 未结 5 2104
情深已故
情深已故 2021-01-06 06:19

I have been working with timezone conversions lately and am quite astonished by the result i get.Basically, i want to convert a date from one timezone into another. below is

5条回答
  •  青春惊慌失措
    2021-01-06 06:58

    The answer is partly explained in a commented section in setTimeZone():

    Consider the sequence of calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST). Is cal set to 1 o'clock EST or 1 o'clock PST? Answer: PST. More generally, a call to setTimeZone() affects calls to set() BEFORE AND AFTER it up to the next call to complete().

    In other words, the sequence

    1. Set Calendar time
    2. Change TimeZone

    is interpreted to mean "Use this time in this new time zone", while the sequence

    1. Set Calendar time
    2. Get the time (or some part of it)
    3. Change Time Zone

    will be interpreted as "Use this time in the old time zone, then change it".

    So, in your case, to get the behavior you are hoping for, you will need to call get(), or any other method that internally calls complete() inside the Calendar, before you change the time zone.

提交回复
热议问题