FileDocCategorySizeDatePackage
TimeZone.javaAPI DocJava SE 6 API25575Tue Jun 10 00:25:56 BST 2008java.util

TimeZone

public abstract class TimeZone extends Object implements Serializable, Cloneable
TimeZone represents a time zone offset, and also figures out daylight savings.

Typically, you get a TimeZone using getDefault which creates a TimeZone based on the time zone where the program is running. For example, for a program running in Japan, getDefault creates a TimeZone object based on Japanese Standard Time.

You can also get a TimeZone using getTimeZone along with a time zone ID. For instance, the time zone ID for the U.S. Pacific Time zone is "America/Los_Angeles". So, you can get a U.S. Pacific Time TimeZone object with:

TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
You can use the getAvailableIDs method to iterate through all the supported time zone IDs. You can then choose a supported ID to get a TimeZone. If the time zone you want is not represented by one of the supported IDs, then a custom time zone ID can be specified to produce a TimeZone. The syntax of a custom time zone ID is:
CustomID:
GMT Sign Hours : Minutes
GMT Sign Hours Minutes
GMT Sign Hours
Sign: one of
+ -
Hours:
Digit
Digit Digit
Minutes:
Digit Digit
Digit: one of
0 1 2 3 4 5 6 7 8 9
Hours must be between 0 to 23 and Minutes must be between 00 to 59. For example, "GMT+10" and "GMT+0010" mean ten hours and ten minutes ahead of GMT, respectively.

The format is locale independent and digits must be taken from the Basic Latin block of the Unicode standard. No daylight saving time transition schedule can be specified with a custom time zone ID. If the specified string doesn't match the syntax, "GMT" is used.

When creating a TimeZone, the specified custom time zone ID is normalized in the following syntax:

NormalizedCustomID:
GMT Sign TwoDigitHours : Minutes
Sign: one of
+ -
TwoDigitHours:
Digit Digit
Minutes:
Digit Digit
Digit: one of
0 1 2 3 4 5 6 7 8 9
For example, TimeZone.getTimeZone("GMT-8").getID() returns "GMT-08:00".

Three-letter time zone IDs

For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.
see
Calendar
see
GregorianCalendar
see
SimpleTimeZone
version
1.75 11/30/05
author
Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
since
JDK1.1

Fields Summary
public static final int
SHORT
A style specifier for getDisplayName() indicating a short name, such as "PST."
public static final int
LONG
A style specifier for getDisplayName() indicating a long name, such as "Pacific Standard Time."
private static final int
ONE_MINUTE
private static final int
ONE_HOUR
private static final int
ONE_DAY
private static Hashtable
cachedLocaleData
Cache to hold the SimpleDateFormat objects for a Locale.
static final long
serialVersionUID
static final TimeZone
NO_TIMEZONE
The null constant as a TimeZone.
private String
ID
The string identifier of this TimeZone. This is a programmatic identifier used internally to look up TimeZone objects from the system table and also to map them to their localized display names. ID values are unique in the system table but may not be for dynamically created zones.
private static volatile TimeZone
defaultTimeZone
private static final InheritableThreadLocal
defaultZoneTL
static final String
GMT_ID
private static final int
GMT_ID_LENGTH
Constructors Summary
public TimeZone()
Sole constructor. (For invocation by subclass constructors, typically implicit.)

    
Methods Summary
public java.lang.Objectclone()
Creates a copy of this TimeZone.

return
a clone of this TimeZone

        try {
            TimeZone other = (TimeZone) super.clone();
            other.ID = ID;
            return other;
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    
public static synchronized java.lang.String[]getAvailableIDs(int rawOffset)
Gets the available IDs according to the given time zone offset in milliseconds.

param
rawOffset the given time zone GMT offset in milliseconds.
return
an array of IDs, where the time zone for that ID has the specified GMT offset. For example, "America/Phoenix" and "America/Denver" both have GMT-07:00, but differ in daylight savings behavior.
see
#getRawOffset()

	return ZoneInfo.getAvailableIDs(rawOffset);
    
public static synchronized java.lang.String[]getAvailableIDs()
Gets all the available IDs supported.

return
an array of IDs.

	return ZoneInfo.getAvailableIDs();
    
public intgetDSTSavings()
Returns the amount of time to be added to local standard time to get local wall clock time.

The default implementation always returns 3600000 milliseconds (i.e., one hour) if this time zone observes Daylight Saving Time. Otherwise, 0 (zero) is returned.

If an underlying TimeZone implementation subclass supports historical Daylight Saving Time changes, this method returns the known latest daylight saving value.

return
the amount of saving time in milliseconds
since
1.4

	if (useDaylightTime()) {
	    return 3600000;
	}
	return 0;
    
public static java.util.TimeZonegetDefault()
Gets the default TimeZone for this host. The source of the default TimeZone may vary with implementation.

return
a default TimeZone.
see
#setDefault

        return (TimeZone) getDefaultRef().clone();
    
static java.util.TimeZonegetDefaultRef()
Returns the reference to the default TimeZone object. This method doesn't create a clone.

	TimeZone defaultZone = defaultZoneTL.get();
	if (defaultZone == null) {
	    defaultZone = defaultTimeZone;
	    if (defaultZone == null) {
		// Need to initialize the default time zone.
		defaultZone = setDefaultZone();
		assert defaultZone != null;
	    }
	}
	// Don't clone here.
	return defaultZone;
    
public final java.lang.StringgetDisplayName(java.util.Locale locale)
Returns a name of this time zone suitable for presentation to the user in the specified locale. This method returns the long name, not including daylight savings. If the display name is not available for the locale, then this method returns a string in the normalized custom ID format.

param
locale the locale in which to supply the display name.
return
the human-readable name of this time zone in the given locale.
since
1.2

        return getDisplayName(false, LONG, locale);
    
public final java.lang.StringgetDisplayName(boolean daylight, int style)
Returns a name of this time zone suitable for presentation to the user in the default locale. If the display name is not available for the locale, then this method returns a string in the normalized custom ID format.

param
daylight if true, return the daylight savings name.
param
style either LONG or SHORT
return
the human-readable name of this time zone in the default locale.
since
1.2

        return getDisplayName(daylight, style, Locale.getDefault());
    
public java.lang.StringgetDisplayName(boolean daylight, int style, java.util.Locale locale)
Returns a name of this time zone suitable for presentation to the user in the specified locale. If the display name is not available for the locale, then this method returns a string in the normalized custom ID format.

param
daylight if true, return the daylight savings name.
param
style either LONG or SHORT
param
locale the locale in which to supply the display name.
return
the human-readable name of this time zone in the given locale.
exception
IllegalArgumentException style is invalid.
since
1.2

        if (style != SHORT && style != LONG) {
            throw new IllegalArgumentException("Illegal style: " + style);
        }

	String id = getID();
	String[] names = getDisplayNames(id, locale);
	if (names == null) {
	    if (id.startsWith("GMT")) {
		char sign = id.charAt(3);
		if (sign == '+" || sign == '-") {
		    return id;
		}
	    }
	    int offset = getRawOffset();
	    if (daylight) {
		offset += getDSTSavings();
	    }
	    return ZoneInfoFile.toCustomID(offset);
	}

	int index = daylight ? 3 : 1;
	if (style == SHORT) {
	    index++;
	}
	return names[index];
    
public final java.lang.StringgetDisplayName()
Returns a name of this time zone suitable for presentation to the user in the default locale. This method returns the long name, not including daylight savings. If the display name is not available for the locale, then this method returns a string in the normalized custom ID format.

return
the human-readable name of this time zone in the default locale.
since
1.2

        return getDisplayName(false, LONG, Locale.getDefault());
    
private static final java.lang.String[]getDisplayNames(java.lang.String id, java.util.Locale locale)

    

            
	Map<String, SoftReference<Map<Locale, String[]>>> displayNames = DisplayNames.CACHE;

	SoftReference<Map<Locale, String[]>> ref = displayNames.get(id);
	if (ref != null) {
	    Map<Locale, String[]> perLocale = ref.get();
	    if (perLocale != null) {
		String[] names = perLocale.get(locale);
		if (names != null) {
		    return names;
		}
		names = TimeZoneNameUtility.retrieveDisplayNames(id, locale);
		if (names != null) {
		    perLocale.put(locale, names);
		}
		return names;
	    }
	}

	String[] names = TimeZoneNameUtility.retrieveDisplayNames(id, locale);
	if (names != null) {
	    Map<Locale, String[]> perLocale = new ConcurrentHashMap<Locale, String[]>();
	    perLocale.put(locale, names);
	    ref = new SoftReference<Map<Locale, String[]>>(perLocale);
	    displayNames.put(id, ref);
	}
	return names;
    
public java.lang.StringgetID()
Gets the ID of this time zone.

return
the ID of this time zone.

        return ID;
    
public abstract intgetOffset(int era, int year, int month, int day, int dayOfWeek, int milliseconds)
Gets the time zone offset, for current date, modified in case of daylight savings. This is the offset to add to UTC to get local time.

This method returns a historically correct offset if an underlying TimeZone implementation subclass supports historical Daylight Saving Time schedule and GMT offset changes.

param
era the era of the given date.
param
year the year in the given date.
param
month the month in the given date. Month is 0-based. e.g., 0 for January.
param
day the day-in-month of the given date.
param
dayOfWeek the day-of-week of the given date.
param
milliseconds the milliseconds in day in standard local time.
return
the offset in milliseconds to add to GMT to get local time.
see
Calendar#ZONE_OFFSET
see
Calendar#DST_OFFSET

public intgetOffset(long date)
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.

This method returns a historically correct offset value if an underlying TimeZone implementation subclass supports historical Daylight Saving Time schedule and GMT offset changes.

param
date the date represented in milliseconds since January 1, 1970 00:00:00 GMT
return
the amount of time in milliseconds to add to UTC to get local time.
see
Calendar#ZONE_OFFSET
see
Calendar#DST_OFFSET
since
1.4


                                                                                                                                     
              
                                     

                                                                                                       
        
	if (inDaylightTime(new Date(date))) {
	    return getRawOffset() + getDSTSavings();
	}
	return getRawOffset();
    
intgetOffsets(long date, int[] offsets)
Gets the raw GMT offset and the amount of daylight saving of this time zone at the given time.

param
date the milliseconds (since January 1, 1970, 00:00:00.000 GMT) at which the time zone offset and daylight saving amount are found
param
offset an array of int where the raw GMT offset (offset[0]) and daylight saving amount (offset[1]) are stored, or null if those values are not needed. The method assumes that the length of the given array is two or larger.
return
the total amount of the raw GMT offset and daylight saving at the specified date.
see
Calendar#ZONE_OFFSET
see
Calendar#DST_OFFSET

	int rawoffset = getRawOffset();
	int dstoffset = 0;
	if (inDaylightTime(new Date(date))) {
	    dstoffset = getDSTSavings();
	}
	if (offsets != null) {
	    offsets[0] = rawoffset;
	    offsets[1] = dstoffset;
	}
	return rawoffset + dstoffset;
    
public abstract intgetRawOffset()
Returns the amount of time in milliseconds to add to UTC to get standard time in this time zone. Because this value is not affected by daylight saving time, it is called raw offset.

If an underlying TimeZone implementation subclass supports historical GMT offset changes, the method returns the raw offset value of the current date. In Honolulu, for example, its raw offset changed from GMT-10:30 to GMT-10:00 in 1947, and this method always returns -36000000 milliseconds (i.e., -10 hours).

return
the amount of raw offset time in milliseconds to add to UTC.
see
Calendar#ZONE_OFFSET

private static native java.lang.StringgetSystemGMTOffsetID()
Gets the custom time zone ID based on the GMT offset of the platform. (e.g., "GMT+08:00")

private static native java.lang.StringgetSystemTimeZoneID(java.lang.String javaHome, java.lang.String country)
Gets the platform defined TimeZone ID.

public static synchronized java.util.TimeZonegetTimeZone(java.lang.String ID)
Gets the TimeZone for the given ID.

param
ID the ID for a TimeZone, either an abbreviation such as "PST", a full name such as "America/Los_Angeles", or a custom ID such as "GMT-8:00". Note that the support of abbreviations is for JDK 1.1.x compatibility only and full names should be used.
return
the specified TimeZone, or the GMT zone if the given ID cannot be understood.

	return getTimeZone(ID, true);
    
private static java.util.TimeZonegetTimeZone(java.lang.String ID, boolean fallback)

	TimeZone tz = ZoneInfo.getTimeZone(ID);
	if (tz == null) {
	    tz = parseCustomTimeZone(ID);
	    if (tz == null && fallback) {
		tz = new ZoneInfo(GMT_ID, 0);
	    }
	}
	return tz;
    
private static booleanhasPermission()

	boolean hasPermission = true;
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
	    try {
		sm.checkPermission(new PropertyPermission
				   ("user.timezone", "write"));
	    } catch (SecurityException e) {
		hasPermission = false;
	    }
	}
	return hasPermission;
    
public booleanhasSameRules(java.util.TimeZone other)
Returns true if this zone has the same rule and offset as another zone. That is, if this zone differs only in ID, if at all. Returns false if the other zone is null.

param
other the TimeZone object to be compared with
return
true if the other zone is not null and is the same as this one, with the possible exception of the ID
since
1.2

        return other != null && getRawOffset() == other.getRawOffset() &&
            useDaylightTime() == other.useDaylightTime();
    
public abstract booleaninDaylightTime(java.util.Date date)
Queries if the given date is in daylight savings time in this time zone.

param
date the given Date.
return
true if the given date is in daylight savings time, false, otherwise.

private static final java.util.TimeZoneparseCustomTimeZone(java.lang.String id)
Parses a custom time zone identifier and returns a corresponding zone. This method doesn't support the RFC 822 time zone format. (e.g., +hhmm)

param
id a string of the custom ID form.
return
a newly created TimeZone with the given offset and no daylight saving time, or null if the id cannot be parsed.


                                                                
          
	int length;

	// Error if the length of id isn't long enough or id doesn't
	// start with "GMT".
	if ((length = id.length()) < (GMT_ID_LENGTH + 2) ||
	    id.indexOf(GMT_ID) != 0) {
	    return null;
	}

	ZoneInfo zi;

	// First, we try to find it in the cache with the given
	// id. Even the id is not normalized, the returned ZoneInfo
	// should have its normalized id.
	zi = ZoneInfoFile.getZoneInfo(id);
	if (zi != null) {
	    return zi;
	}

	int index = GMT_ID_LENGTH;
	boolean negative = false;
	char c = id.charAt(index++);
	if (c == '-") {
	    negative = true;
	} else if (c != '+") {
	    return null;
	}

	int hours = 0;
	int num = 0;
	int countDelim = 0;
	int len = 0;
	while (index < length) {
	    c = id.charAt(index++);
	    if (c == ':") {
		if (countDelim > 0) {
		    return null;
		}
		if (len > 2) {
		    return null;
		}
		hours = num;
		countDelim++;
		num = 0;
		len = 0;
		continue;
	    }
	    if (c < '0" || c > '9") {
		return null;
	    }
	    num = num * 10 + (c - '0");
	    len++;
	}
	if (index != length) {
	    return null;
	}
	if (countDelim == 0) {
	    if (len <= 2) {
		hours = num;
		num = 0;
	    } else {
		hours = num / 100;
		num %= 100;
	    }
	} else {
	    if (len != 2) {
		return null;
	    }
	}
	if (hours > 23 || num > 59) {
	    return null;
	}
	int gmtOffset =  (hours * 60 + num) * 60 * 1000;

	if (gmtOffset == 0) {
	    zi = ZoneInfoFile.getZoneInfo(GMT_ID);
	    if (negative) {
		zi.setID("GMT-00:00");
	    } else {
		zi.setID("GMT+00:00");
	    }
	} else {
	    zi = ZoneInfoFile.getCustomTimeZone(id, negative ? -gmtOffset : gmtOffset);
	}
	return zi;
    
public static voidsetDefault(java.util.TimeZone zone)
Sets the TimeZone that is returned by the getDefault method. If zone is null, reset the default to the value it had originally when the VM first started.

param
zone the new default time zone
see
#getDefault

	if (hasPermission()) {
	    synchronized (TimeZone.class) {
		defaultTimeZone = zone;
	    }
	} else {
	    defaultZoneTL.set(zone);
	}
    
private static synchronized java.util.TimeZonesetDefaultZone()

	TimeZone tz = null;
	// get the time zone ID from the system properties
	String zoneID = AccessController.doPrivileged(
		new GetPropertyAction("user.timezone"));

	// if the time zone ID is not set (yet), perform the
	// platform to Java time zone ID mapping.
	if (zoneID == null || zoneID.equals("")) { 
	    String country = AccessController.doPrivileged(
		    new GetPropertyAction("user.country"));
	    String javaHome = AccessController.doPrivileged(
		    new GetPropertyAction("java.home"));
	    try {
		zoneID = getSystemTimeZoneID(javaHome, country);
		if (zoneID == null) {
		    zoneID = GMT_ID;
		}
	    } catch (NullPointerException e) {
		zoneID = GMT_ID;
	    }
	}

	// Get the time zone for zoneID. But not fall back to
	// "GMT" here.
	tz = getTimeZone(zoneID, false);

	if (tz == null) {
	    // If the given zone ID is unknown in Java, try to
	    // get the GMT-offset-based time zone ID,
	    // a.k.a. custom time zone ID (e.g., "GMT-08:00").
	    String gmtOffsetID = getSystemGMTOffsetID();
	    if (gmtOffsetID != null) {
		zoneID = gmtOffsetID;
	    }
	    tz = getTimeZone(zoneID, true);
	}
	assert tz != null;

	final String id = zoneID;
	AccessController.doPrivileged(new PrivilegedAction<Object>() {
		public Object run() {
		    System.setProperty("user.timezone", id);
		    return null;
		}
	    });

	if (hasPermission()) {
	    defaultTimeZone = tz;
	} else {
	    defaultZoneTL.set(tz);
	}
	return tz;
    
public voidsetID(java.lang.String ID)
Sets the time zone ID. This does not change any other data in the time zone object.

param
ID the new time zone ID.

        if (ID == null) {
            throw new NullPointerException();
        }
        this.ID = ID;
    
public abstract voidsetRawOffset(int offsetMillis)
Sets the base time zone offset to GMT. This is the offset to add to UTC to get local time.

If an underlying TimeZone implementation subclass supports historical GMT offset changes, the specified GMT offset is set as the latest GMT offset and the difference from the known latest GMT offset value is used to adjust all historical GMT offset values.

param
offsetMillis the given base time zone offset to GMT.

public abstract booleanuseDaylightTime()
Queries if this time zone uses daylight savings time.

If an underlying TimeZone implementation subclass supports historical Daylight Saving Time schedule changes, the method refers to the latest Daylight Saving Time schedule information.

return
true if this time zone uses daylight savings time, false, otherwise.