Hi I have a following code below:
public Date convertFromGMTToLocal(Date date) {
return new Date(date.getTimezoneOffset() + newOffset*60*1000);
}
public Date convertFromLocalToGMT(Date date) {
return new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
}
convertFromLocalToGMT is supposed to strip off timezone information and convertFromGMTToLocal is supposed to put the timezone information back. I understand java.util.Date is representing the time in epoch and always in GMT however when displaying the date it is defaulted to JVM’s default timezone.
Explanation I got was that if your timezone is CST and it is 10:00AM CST you are changing timezone to GMT with convertFromLocalToGMT so you’re essentially adding the offset to get GMT so you get 4:00AM CST (offset is -6) and using convertFromGMTToLocal will convert this Date object back to 10:00AM regardless of your timezones (the most confusing part how?). How does above work? I am confused…
Thanks.
You should pretty much never add an offset to a
Dateto create anotherDate– you’d only ever do that if you received broken data to start with.You should not use this code. It is bad code which tries to treat
java.util.Datein a way it was not designed for. If you want to represent a date in a particular time zone, either useCalendar(urgh) or the far better Joda Time API.In particular, the code you’ve got will not work around time zone transitions – because the offset at
date.getTimeZoneOffset()still considersdateto be UTC (because that’s what it’s defined as) even you’re treating it as a local date/time.Ignore the value that’s displayed by
Date.toString()– avoid using that method. Either display usingSimpleDateFormatwith appropriate settings for the time zone you’re interested in, or (better, again) use Joda’sDateTimeFormatclass.