Convert Java Date To GMT
Join the DZone community and get the full member experience.
Join For FreeThis function converts a local date to GMT. This version corrects the bug common to this type of conversion where the date is incorrectly converted when the time is close to the DST crossover. WARNING: This code is for printing/string-representation only, the millis value of the returned date is NOT in GMT.
private static Date cvtToGmt( Date date )
{
TimeZone tz = TimeZone.getDefault();
Date ret = new Date( date.getTime() - tz.getRawOffset() );
// if we are now in DST, back off by the delta. Note that we are checking the GMT date, this is the KEY.
if ( tz.inDaylightTime( ret ))
{
Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );
// check to make sure we have not crossed back into standard time
// this happens when we are on the cusp of DST (7pm the day before the change for PDT)
if ( tz.inDaylightTime( dstDate ))
{
ret = dstDate;
}
}
return ret;
}
Java (programming language)
Convert (command)
Opinions expressed by DZone contributors are their own.
Comments