Java Time: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 65: Line 65:
</pre>
</pre>


 
==Figuring the Time Offset of a Certain Time Zone on a Certain Date==
 
 
 
 


=Offset of a GMT Timestamp Relative to a TimeZone=
=Offset of a GMT Timestamp Relative to a TimeZone=

Revision as of 22:09, 13 July 2016

Internal

Time Zone

The JVM obtains the default time zone from the system. For more details, see time zone. If JVM fails to identify the time zone set externally, it defaults to GMT.

The default time zone in the JVM can be obtained by the Java programs with the following API:

TimeZone dt = TimeZone.getDefault();

A TimeZone instance for a specific time zone can be built by specifying a time zone identifier as String. For example, the GMT (UTC) time zone can be built with:

TimeZone tz = TimeZone.getTimeZone("GMT+0000")

The "GMT-0800" time one can be built with:

TimeZone tz = TimeZone.getTimeZone("GMT-0800")

The timezone instance can be queried for its standard name ("Eastern Standard Time") and ID ("America/New_York").

Raw Time Zone Offset

We can get the amount of milliseconds to apply to UTC to get the standard time in a certain time zone (the standard time offset) with TimeZone.getRawOffset().

This value is not affected by daylight saving time.

TimeZone tz = ...
tz.getRawOffset()

Daylight Saving Time Offset

We can get the amount of time to be added to local standard time to get local wall clock time correctly adjusted for daylight time saving.

TimeZone tz = ...
tz.getDSTSavings();

The method implementation checks for whether the daylight savings time is in effect and returns 1 hour or 0:

public int getDSTSavings() {
    if (useDaylightTime()) {
        return 3600000;
    }
    return 0;
}

Figuring Out Whether Daylight Saving is in Effect for a Certain Date

Date d = ...
inDaylightTime(d); 

Figuring the Time Offset of a Certain Time Zone on a Certain Date

Offset of a GMT Timestamp Relative to a TimeZone

Given a TimeZone instance, it can return the offset to a specified GMT timestamp with:

TimeZone tz = ...
long gmt = ...
tz.getOffset(gmt);

The method returns the offset of this time zone from UTC at the specified date. If Daylight Saving Time is in effect at the specified date, the offset value is adjusted with the amount of daylight saving.


DateFormat and Timezone

java DateFormat Timezone