Java Time: Difference between revisions

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


=DateFormat and Timezone=
==Time Zone and <tt>DateFormat</tt>==


<blockquote style="background-color: #f9f9f9; border: solid thin lightgrey;">
<blockquote style="background-color: #f9f9f9; border: solid thin lightgrey;">
:[[java DateFormat Timezone]]
:[[java DateFormat Timezone]]
</blockquote>
</blockquote>

Revision as of 22:12, 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

Given a TimeZone instance, we can get the time offset to UTC at a certain date (specified as a UTC timestamp). The date is important because the daylight savings may or may not be in effect, and that influences the effective offset:

TimeZone tz = ...
Date date = new Date()
tz.getOffset(date.getTime());

Time Zone and DateFormat

java DateFormat Timezone