Explain the usage of time zone class timezone in Java _java

Source: Internet
Author: User
Tags dateformat time zones locale time and date

Introduction of TimeZone
TimeZone represents the time zone offset, or it can calculate daylight savings.
TimeZone is often used when manipulating dates, calendar, and so on to represent date/time objects, because of different time zones.
Here are 2 common ways to create timezone objects.
1. Get the default TimeZone object
How to use:

TimeZone TZ = Timezone.getdefault ()

2. Use the getTimeZone (String id) method to get the TimeZone object
How to use:

Gets the time zone corresponding to "gmt+08:00"
TimeZone-Timezone.gettimezone ("gmt+:08:00");
Get "China/Chongqing" corresponding time zone
TimeZone chongqing = Timezone.gettimezone ("asia/chongqing");

The value of all ID parameters supported in this way by getTimeZone (String ID) can be found in the following ways:

string[] ids = Timezone.getavailableids ();
for (String id:ids) 
 System.out.printf (id+ ",");

Output results:

Etc/gmt+12, Etc/gmt+11, Pacific/midway, Pacific/niue .... Wait a minute
For example, create a timezone corresponding to the 2nd printed value "Etc/gmt+11" above. The method is as follows:
TimeZone TZ = Timezone.gettimezone ("etc/gmt+11");
TimeZone function Interface
TimeZone ():
 Object clone () synchronized static string[] Getavailableids () synchronized static St Ring[] Getavailableids (int offsetmillis) int getdstsavings () synchronized static TimeZone Getdefault () Final String g Etdisplayname (Locale Locale) string GetDisplayName (boolean daylighttime, int style, Locale Locale) final string getdi Splayname () Final String GetDisplayName (boolean daylighttime, int style) string GetID () abstract int getoffset (int ERA, int year, int month, int day, int dayofweek, int timeofdaymillis) int getoffset (long time) abstract int getrawof Fset () synchronized static TimeZone getTimeZone (String id) boolean hassamerules (TimeZone TimeZone) Abstract Boolean I   Ndaylighttime (Date time) synchronized static void SetDefault (TimeZone TimeZone) void SetID (String id) abstract void Setrawoffset (int offsetmillis) Abstract Boolean usedaylighttime () 

Two, timezone example:
The following example shows the use of timezone in date. The
Reference code is as follows (Timezonetest.java):

Import Java.text.DateFormat;
Import Java.util.Date;

Import Java.util.TimeZone;
 /** * TimeZone test program/public class Timezonetest {public static void main (string[] args) {//test 3 ways to create a TimeZone object

 Showusageoftimezones ();

 Test TimeZone other API Testotherapis ();
 Print all ID//printalltimezones () supported by getTimeZone (String ID);

 /** * Test 3 methods for creating TimeZone objects * * public static void Showusageoftimezones () {TimeZone tz;
 (01) Default time Zone TZ = Timezone.getdefault ();

 Printdatein (TZ);
 (02) Setting the time zone to "gmt+08:00" TZ = Timezone.gettimezone ("gmt+08:00");

 Printdatein (TZ);
 (03) Set the time zone to "" TZ = Timezone.gettimezone ("asia/chongqing");
 Printdatein (TZ);  /** * Print TZ corresponding Date/time */private static void Printdatein (TimeZone tz) {//date is 2013-09-19 14:22:30 date = new
 Date (113, 8, 19, 14, 22, 30);
 Gets the default DateFormat, which is used to format the date DateFormat df = Dateformat.getinstance ();
 Set the time zone to TZ Df.settimezone (TZ);

 Gets the formatted string, string str = Df.format (date); System.out.println (Tz.getid () + ": "+str);

 /** * Test TimeZone Other APIs */public static void Testotherapis () {//default time zone TimeZone TZ = Timezone.getdefault ();

 Gets the id String id = tz.getid ();

 Gets the display name String name = Tz.getdisplayname (); Gets the time offset.
 Relative to the "meridian" offset, the unit is Ms.
 int offset = Tz.getrawoffset ();

 Gets the time offset corresponds to the hour int GMT = offset/(3600*1000);
 System.out.printf ("id=%s, name=%s, offset=%s (ms), gmt=%s\n", ID, name, offset, GMT); All ID/public static void Printalltimezones () {string[] IDs supported by/** * Print gettimezone (String id) = Timezone.getavai
 Lableids ();
  for (String id:ids) {//int offset = Timezone.gettimezone (Avaids[i]). Getrawoffset ();
  System.out.println (i+ "" +avaids[i]+ "" +offset/(3600 * 1000) + "T");
 System.out.printf (id+ ",");
 } System.out.println ();


Iii. about timezone and time calibration
Java and Solaris are similar when it comes to information about time zones. Each time area has a time area ID identifier. In J2SE 1.3 and 1.4, this ID is a string and is a list of these IDs by tzmappings files located in the Jre/lib subdirectory of the J2SE installer. J2SE 1.3 contains only tzmappings files, but J2SE 1.4 contains data files for time zones in different parts of the world. Jre/lib/zi store these files. In J2SE 1.4, Sun.util.calendar.ZoneInfo obtains DST rules from these files. In Solaris, these time zone data files are stored in binary form, not as text files, so you can't look at them. The time zone data files in J2SE 1.4 are different from those in Solaris.

The source code for the Getdefault method in the Java.util.TimeZone class shows that it will eventually invoke the getTimeZone method of the Sun.util.calendar.ZoneInfo class. This method returns a string parameter as an ID for the required time range. This default time zone ID is obtained from the User.timezone (System) attribute. If User.timezone is not defined, it attempts to obtain an ID from the User.country and Java.home (System) properties. If it does not successfully find a time area ID, it uses a "fallback" GMT value. In other words, if it does not compute your time area ID, it will use GMT as your default time zone.

Note that the system property is initialized in the InitProperties method of the Java.lang.System class. This is a local method. Therefore, the source code is not available----unless you delve into the local code base in the J2SE distribution. However, in Windows systems, the system properties are initialized from the Windows registry and are initialized by environment variables in Linux/unix. The Javadoc declaration of the InitProperties method, some attributes "must be guaranteed to be defined" and list them. Of the three system properties used by the Getdefault method of the Java.util.TimeZone class, only Java.home is listed as a "guaranteed" attribute in Javadoc.

Recommended Solutions:
So how do you make sure that Java can give you the right time and date? The best way to do this is to make sure that the default timezone class for the Java Virtual Machine (JVM) is correct and is appropriate for your geographic scope (Locale). How do you make sure that the default timezone is correct and appropriate? This is a new problem again. As with most of the problems dealt with, this also has a number of solutions. According to the source code of the Java.util.TimeZone.getDefault method, the best way is to set the User.timezone property correctly. When you start a Java Virtual machine, you can easily override (override) the values set in the Java.lang.System.initProperties method by using the-d command-line parameters. For example:

Java-duser.timezone=asia/shanghai Datetest 

This command starts the Datetest class and sets the User.timezone property to Asia/shanghai. You can also set the User.timezone property by using the SetProperty method of the Java.lang.System class:

System.setproperty ("User.timezone", "Asia/shanghai"); 

If you don't have an available time zone ID for you, then you can create a custom TimeZone using the SetDefault method of the Java.util.TimeZone class to set it as the default time zone----Just like I was in Itsinitializer In the same way as you do in a class.

Remember, in J2SE, most date and time related classes contain time zone information, including those format classes, such as Java.text.DateFormat, so they are all affected by the JVM's default time zone. However, when you create instances of these classes, you can ensure the correct time zone information for them, making it easier for you to set the default time zone for the entire JVM. And once you've set it up, you can make sure that all of these classes will use the same default time zone.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.