Java Universal Conversion processing method for all time zones (TimeZone) in the world

Source: Internet
Author: User
Tags time zones

In the process of international software project development, sometimes encounter some more special requirements. For example, you do a shopping site (assuming the server is placed in Shanghai, China), when the world's customers on your website orders to buy things, often want to see the location of the customer place time, for example, I am a New Yorker in the United States, I on your website after the order, you show me a Shanghai order time, Would feel very strange. As we all know, New York time is about 13 hours later than Shanghai time, if let customer see time of local time zone, will become more in line with customer's time concept, make customer understand more convenient.

In fact, Java has already considered the problem of the world Time Zone (TimeZone), and gives a more reasonable solution, it can be more convenient for the conversion of the time of the global timezone, the time of one time zone into another time zone. Take a look at the following practical example (the main () method that runs the example).

For information on how to know your customer's time zone, you can calculate your time zone based on the IP of the customer or the country you are registering with.

/** Created on 2005-6-10 * Author Stephen * e-mail zhoujianqiang at gmail DOT com * CopyRight (C) 2005-2008, All rights R Eserved. */ Packagecom.soft4j.utility;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJava.util.GregorianCalendar;ImportJava.util.TimeZone;ImportJava.util.Vector;ImportCom.soft4j.log.Log;/*** Some common tool methods related to date and time. * <p> * Date (time) commonly used format (Formater) mainly include: <br> * YYYY-MM-DD HH:mm:ss <br> * *@authorStephen *@version1.0.0*/ Public Final classDatetool {/*** Add and subtract days from date (time). <br> * Example: <br> * If date type D is August 20, 2005, then <br> * Calculateby The value of Date (d,-10) is August 10, 2005 <br> * and Calculatebydate (D,+10) has a value of August 30, 2005 <br> * *@paramd * Date (time). * @paramAmount * Add and subtract the amplitude of the calculation. +n= n days;-n= minus n days. * @returnthe date (time) after the calculation. */     Public StaticDate Calculatebydate (Date D,intamount) {        returnCalculate (d, gregoriancalendar.date, amount); }         Public StaticDate Calculatebyminute (Date D,intamount) {        returnCalculate (d, gregoriancalendar.minute, amount); }         Public StaticDate Calculatebyyear (Date D,intamount) {        returnCalculate (d, gregoriancalendar.year, amount); }    /*** Add and subtract the date members specified by the field parameter in the date (time). <br> * Example: <br> * If date type D is August 20, 2005, then <br> * The value of calculate (d,gregoriancalendar.year,-10) is August 20, 1995 <br> * and calculate (d,gregoriancalendar.year,+10) The value is August 20, 2015 <br> * *@paramd * Date (time). * @paramfield * Date member. <br> * Date members mainly include: <br> * Year: Gregoriancalendar.yea     R <br> * Month: Gregoriancalendar.month <br> * Day: Gregoriancalendar.date <br>            * Hours: Gregoriancalendar.hour <br> * points: Gregoriancalendar.minute <br> * Seconds: Gregoriancalendar.second <br> * MS: Gregoriancalendar.millisecond <br> *@paramAmount * Add and subtract the amplitude of the calculation. +n= n the date member value specified by the parameter field,-n= minus n is the date member value represented by the argument field. * @returnthe date (time) after the calculation. */    Private StaticDate Calculate (Date D,intFieldintamount) {        if(d = =NULL)            return NULL; GregorianCalendar g=NewGregorianCalendar ();        G.setgregorianchange (d);        G.add (field, amount); returnG.gettime (); }    /*** Date (time) converted to string. *      * @paramformater * Format of date or time. * @paramAdate * An instance of the Java.util.Date class. * @returnthe date-converted string. */     Public Staticstring date2string (String formater, Date adate) {if(Formater = =NULL|| "". Equals (formater))return NULL; if(Adate = =NULL)            return NULL; return(NewSimpleDateFormat (Formater)). Format (adate); }    /*** The current date (time) is converted to a string. *      * @paramformater * Format of date or time. * @returnthe date-converted string. */     Public Staticstring date2string (String formater) {returnDate2string (Formater,NewDate ()); }        /*** Gets the number of weeks that the current date corresponds to. * <br>1= Sunday, 2 = Monday, 3 = Tuesday, 4 = Wednesday, 5 = Thursday, 6 = Friday, 7 = Saturday *@returnthe number of weeks that the current date corresponds to*/     Public Static intDayOfWeek () {GregorianCalendar g=NewGregorianCalendar (); intRET =G.get (Java.util.Calendar.DAY_OF_WEEK); G=NULL; returnret; }    /*** Get all time zone numbers. <br> * Collation: Sort by the positive order of the ASCII characters. <br> * Sorting ignores character case. *      * @returnAll time zone numbers (time zone numbers are sorted by character [ignore case]). */     Public Staticstring[] Fecthalltimezoneids () {Vector v=NewVector (); String[] IDs=Timezone.getavailableids ();  for(inti = 0; i < ids.length; i++) {V.add (ids[i]);        } java.util.Collections.sort (V, String.case_insensitive_order);        V.copyinto (IDS); V=NULL; returnIDs; }    /*** Test the Main method. *      * @paramargc*/     Public Static voidMain (string[] argc) {string[] IDs=Fecthalltimezoneids (); String Nowdatetime=date2string ("Yyyy-mm-dd HH:mm:ss"); System.out.println ("The time Asia/shanhai is" + nowdatetime);//program local run time zone is [Asia/shanhai]//show the current actual time in each time zone in the world         for(intI=0;i <ids.length;i++) {System.out.println ("*" + ids[i] + "=" +String2timezonedefault (Nowdatetime,ids[i])); }        //Show the time zone where the program is runningSystem.out.println ("Timezone.getdefault (). GetID () =" +Timezone.getdefault (). GetID ()); }    /*** The datetime string is converted to the date time in the specified time zone. *      * @paramsrcformater * Format of date and time to convert. * @paramSrcdatetime * Date and time to convert. * @paramDstformater * The format of the date time of the target. * @paramDsttimezoneid * The time zone number of the target. *      * @returndate and time after conversion. */     Public Staticstring String2timezone (String srcformater, String srcdatetime, String dstformater, String Dsttimezoneid) { if(Srcformater = =NULL|| "". Equals (srcformater))return NULL; if(Srcdatetime = =NULL|| "". Equals (srcdatetime))return NULL; if(Dstformater = =NULL|| "". Equals (dstformater))return NULL; if(Dsttimezoneid = =NULL|| "". Equals (Dsttimezoneid))return NULL; SimpleDateFormat SDF=NewSimpleDateFormat (Srcformater); Try {            intDifftime =Getdifftimezonerawoffset (Dsttimezoneid); Date D=Sdf.parse (srcdatetime); LongNowtime =D.gettime (); LongNewnowtime = Nowtime-Difftime; D=NewDate (newnowtime); returndate2string (Dstformater, D); } Catch(ParseException e) {log.output (e.tostring (), log.std_err); return NULL; } finally{SDF=NULL; }    }    /*** Gets the time difference between the system's current default timezone and UTC. (Unit: milliseconds) * *@returnthe time difference between the system's current default timezone and UTC. (unit: milliseconds)*/    Private Static intGetdefaulttimezonerawoffset () {returnTimezone.getdefault (). Getrawoffset (); }    /*** Gets the time difference between the specified timezone and UTC. (Unit: milliseconds) * *@paramtimeZoneId * Time zone ID *@returnSpecifies the time difference between the timezone and UTC. (unit: milliseconds)*/    Private Static intGettimezonerawoffset (String timeZoneId) {returnTimezone.gettimezone (timeZoneId). Getrawoffset (); }    /*** Gets the time difference between the system's current default time zone and the specified timezone. (Unit: milliseconds) * *@paramtimeZoneId * Time zone ID *@returnthe time difference between the system's current default timezone and the specified time zone. (unit: milliseconds)*/    Private Static intGetdifftimezonerawoffset (String timeZoneId) {returnTimezone.getdefault (). Getrawoffset ()-Timezone.gettimezone (timeZoneId). Getrawoffset (); }    /*** The datetime string is converted to the date time in the specified time zone. *      * @paramSrcdatetime * Date and time to convert. * @paramDsttimezoneid * The time zone number of the target. *      * @returndate and time after conversion. * @see#string2Timezone (String, String, String, String)*/     Public Staticstring String2timezonedefault (String srcdatetime, String dsttimezoneid) {returnString2timezone ("Yyyy-mm-dd HH:mm:ss", Srcdatetime,"Yyyy-mm-dd HH:mm:ss", Dsttimezoneid); }}

This article transferred from: http://stephen830.iteye.com/blog/260343

Java Universal Conversion processing method for all time zones (TimeZone) in the world

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.