Java Time related content learning (7) TimeZone Introduction

Source: Internet
Author: User
Tags abstract contains dateformat final time zones locale printf time and date


This chapter describes timezone.



TimeZone Introduction



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 using the getTimeZone (String id) method to get the TimeZone object



How to use:


Get the time zone corresponding to "gmt+08:00"
TimeZone-Timezone.gettimezone ("gmt+:08:00");
Get the "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 ....etc.


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 String[] getAvailableIDs(int offsetMillis)
int    getDSTSavings()
synchronized static TimeZone getDefault()
final String   getDisplayName(Locale locale)
String    getDisplayName(boolean daylightTime, int style, Locale locale)
final String   getDisplayName()
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   getRawOffset()
synchronized static TimeZone getTimeZone(String id)
boolean    hasSameRules(TimeZone timeZone)
abstract boolean   inDaylightTime(Date time)
synchronized static void  setDefault(TimeZone timeZone)
void    setID(String id)
abstract void   setRawOffset(int offsetMillis)
abstract boolean   useDaylightTime()
Second, the TimeZone example:
The following example demonstrates 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 other APIs for TimeZone
 testOtherAPIs() ;
 
 // print all ids supported by getTimeZone(String id)
 //printAllTimeZones() ;
 }
 
 
 /**
 * Test 3 ways to create a TimeZone object
 */
 Public static void showUsageOfTimeZones() {
 TimeZone tz;
 
 // (01) Default time zone
 Tz = TimeZone.getDefault();
 printDateIn(tz) ;
 
 // (02) Set 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 the date/time corresponding to tz
 */
 Private static void printDateIn(TimeZone tz) {
 // date is 2013-09-19 14:22:30
 Date date = new Date(113, 8, 19, 14, 22, 30);
 // Get the default DateFormat for formatting Date
 DateFormat df = DateFormat.getInstance();
 / / Set the time zone to tz
 df.setTimeZone(tz);
 / / Get the formatted string
 String str = df.format(date);
 
 System.out.println(tz.getID()+" :"+str);
 }
 
 /**
 * Test other APIs for TimeZone
 */
 Public static void testOtherAPIs() {
 // default time zone
 TimeZone tz = TimeZone.getDefault();
 
 // Get "id"
 String id = tz.getID();
 
 // Get the "display name"
 String name = tz.getDisplayName();
 
 // Get the "time offset". The unit is ms relative to the offset of the "primary meridian".
 Int offset = tz.getRawOffset();
 // Get the hour corresponding to the "time offset"
 Int gmt = offset/(3600*1000);
 
 System.out.printf("id=%s, name=%s, offset=%s(ms), gmt=%s\n",
  Id, name, offset, gmt);
 }
 
 /**
 * Print all ids supported by getTimeZone(String id)
 */
 Public static void printAllTimeZones() {
 
 String[] ids = TimeZone.getAvailableIDs();
 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();
 }
}
Third, about TimeZone and time calibration
Java and Solaris are very similar when it comes to time zone information. Each time zone has a time zone ID identifier. In J2SE 1.3 and 1.4, this ID is a string that is a list of IDs from the tzmappings file located in the jre/lib subdirectory of the J2SE installer. J2SE 1.3 only contains tzmappings files, but J2SE 1.4 contains time zone data files from different parts of the world. Jre/lib/zi stores these files. In J2SE 1.4, sun.util.calendar.ZoneInfo gets DST rules from these files. In Solaris, these time zone data files are stored in binary form, not 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 eventually calls the getTimeZone method of the sun.util.calendar.ZoneInfo class. This method returns a String parameter as an ID for the required time region. This default time zone ID is obtained from the user.timezone (system) property. If user.timezone is not defined, it will try to get the ID from the user.country and java.home (System) properties. If it does not successfully find a time zone ID, it will use a "fallback" GMT value. In other words, if it doesn't calculate your time zone 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. So the source code is not available -- unless you delve into the native code base in the J2SE distribution. However, on Windows systems, the System property is initialized from the Windows registry, and in Linux/Unix it is initialized by environment variables. The Javadoc declaration for the initProperties method, some properties "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" property in the Javadoc.

Recommended solution:

So how do you ensure that JAVA can give you the right time and date? The best way to do this is to verify that the default TimeZone class for the JAVA virtual machine (JVM) is correct and is appropriate for your locale. How do you make sure the default TimeZone is correct and suitable? This is another new issue. As with most processing issues, there are many solutions to this. According to the source code of the java.util.TimeZone.getDefault method, the best way is to set the user.timezone property correctly. When starting a JAVA virtual machine, you can easily override the value set in the java.lang.System.initProperties method by using the -D command -line parameter. E.g:


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 no time zone ID is available for you, then you can create a custom TimeZone using the setDefault method of the java.util.TimeZone class to set it to the default time zone -- just like I was in the ItsInitializer class. The same is true for the operation.

Keep in mind that in J2SE, most date and time related classes contain time zone information, including those of the format, 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 to set the default time zone for the entire JVM. And once set, you can ensure that all of these classes will use the same default time zone.

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.