A general conversion processing method of Java to World time Zones (TimeZone)

Source: Internet
Author: User
Tags time zones local time

In the process of developing international software projects, some special requirements are sometimes encountered. For example, you do a shopping site (assuming the server is in Shanghai, China), when customers all over the world on your site to buy things, often want to see the location of the customer a single time, for example, I am a New Yorker, I am in your site after the list, you show me a Shanghai's next single time, Would feel very strange. As we all know, New York time relative to Shanghai time is about 13 hours, if the customer to see the time of the local time zone, will become more consistent with the concept of customer time, making customers understand more convenient.

In fact, Java has already considered the problem of the World region (TimeZone), and gives a more reasonable solution, it can be more convenient for the time to transform the times, the time zone to convert to another time zone. Take a look at the actual example below (the main () method of the running example).

For information on how to know the time zone of the customer, you can calculate the time zone based on the customer's IP or the country where the user is registered.

Java code  /*    * created on 2005-6-10    * author stephen   & nbsp;* email zhoujianqiang at gmail dot com    * copyright (C) 2005-2008 , all rights reserved.    */   package com.soft4j.utility;       import java.text.parseexception;    import java.text.simpledateformat;    import java.util.date;    import java.util.gregoriancalendar;    import java.util.timezone;    import java.util.vector;       import com.soft4j.log.log;      /**    *  Some common tool methods related to date and time.    * <p>    *  Date (time) common format (formater) mainly has: <br>    *  yyyy-mm-dd hh:mm:ss <br>    *     *  @author  stephen     * @version 1.0.0    */   public final class datetool {          /**        *  the day in the date (time) to add and subtract calculation . < br>        *  Example: <br>        *   If the date type D is  2005 year August 20, then  <br>        * calculatebydate The value for (d,-10) is August 10, 2005  <br>        *  calculatebydate (d,+10) The value is August 30, 2005  <br>        *         *   @param  d        *              Date (time).        *  @param  amount        *              the magnitude of the calculation. +n= plus n days;-n= minus n days.        *  @return   Calculated date (time).        */       public static Date  Calculatebydate (date d, int amount)  {            return calculate (D, gregoriancalendar.date, amount);       &nbsp}                 Public static date calculatebyminute (date d, int amount)  {           return calculate (d, gregoriancalendar.minute,  Amount);       &nbsp}                 Public static date calculatebyyear (date d, int amount)  {            return calculate (D, gregOriancalendar.year, amount);       &nbsp           /**         *  Add and subtract calculation . <br>        * for date members specified by the field parameter in the date (time)   Example: <br>        *  if the date type D is  2005 year August 20, then  <br >        * calculate (d,gregoriancalendar.year,-10) value is August 20, 1995  < br>        *  The value of calculate (d,gregoriancalendar.year,+10) is August 20, 2015   <br>        *         *  @param  d        *             Date (time).        *  @param  field        *              Date members. &Nbsp;<br>        *              Date members mainly have: <br>        *              year:gregoriancalendar.year <br>         *             Month: Gregoriancalendar.month  <br>        *              Day:gregoriancalendar.date <br>        *              Time:gregoriancalendar.hour <br>        *             points: gregoriancalendar.minute <br>        *              sec:gregoriancalendar.second <br>        *              Ms:gregoriancalendar.millisecond <br>        *  @param  amount        *              the magnitude of the calculation. +n= plus n A date member value specified by the parameter field;-n= Minus n A date member value represented by the parameter field.        *  @return   Calculated date (time).        */       private static Date  Calculate (date d, int field, int amount)  {            if  (d == null)                 return null;            gregoriancalendar g = new&nbsP GregorianCalendar ();            g.setgregorianchange (d);            g.add (Field, amount);            return g.gettime ();       &nbsp           /**      The    *  date (time) is converted to a string.        *         *  @param  formater        *             The format of the date or time.        *  @param  adate        *   An instance of the           java.util.date class.        *  @return   Date converted string.        */       Public static string date2string (string formater, date adate)  {           if  (formater == null | |   ". Equals (Formater))                 return null;            if  (adate == null)                return null;            return  (New simpledateformat (Formater)). Format (adate);       &nbsp           /**         *  the current date (time) is converted to a string.        *         *  @param  formater        *       The format of the       date or time.        *  @return   Date converted string.        */       public static String  Date2string (string formater)  {           return  date2string (Formater, new date ());       &nbsp}                / * *        *  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         *  @return   Current date of week        */        public static int dayofweek ()  {            gregoriancalendar g = new gregoriancalendar ();            int ret = g.get (Java.util.Calendar.DAY_OF_WEEK);            g = null;            return ret;       &nbsp              /**        *  get all the time zone numbers . <br>        *  sorting rules : Sort . <br>        *  sort time ignores character capitalization according to the positive order of ASCII characters.        *         *  @return   All time zone numbers ( The time zone number has been sorted by character [ignore case].        */       public static string[]  fecthalltimezoneids ()  {           vector v  = new vector ();            string[] ids = timezone.getavailableids ();            for  (int i = 0; i  < ids.length; i++)  {                v.add (Ids[i]);            }             java.util.collections.sort (V, string.case_insensitive_order);            v.copyinto (IDS);            v = null;            return ids;       &nbsp           /**      The main method of    *  test.        *         *  @param   argc        */       public static void  main (STRING[]&NBSP;ARGC)  {                       string[] ids = fecthalltimezoneids ();            string nowdatetime =date2string (" Yyyy-mm-dd hh:mm:ss ");            system.out.println ("the time asia/ shanhai is  " + nowdatetime);//program Local running time zone is [Asia/shanhai]             //shows the current actual time            for for each time zone in the world (int i=0;i <ids.length;i++) {               system.out.println ("  *  " + ids[i] + " = " + string2timeZonedefault (Nowdatetime,ids[i]);             }             //Displays the time zone of the program running             system.out.println ("Timezone.getdefault (). GetID () ="  +timezone.getdefault (). GetID ());       &nbsp           /**         *  Date time string is converted to the datetime of the specified time zone.        *         *  @param  srcformater        *             The format of the date time to convert.        *  @param  srcdatetime        *              date time to be converted.        *  @param  dstformater    &nbsThe format of the date time for the p;   *             target.        *  @param  dsttimezoneid        * The time zone number for the              target.        *         *  @return   Conversion date time.        */       public static String  String2timezone (String srcformater,                 string srcdatetime, string dstformater, string dsttimezoneid)   {           if  (srcformater == null | |   ". Equals (Srcformater))                 return null;    &NBSP;&NBsp;      if  (srcdatetime == null | |   ". Equals (Srcdatetime))                 return null;            if  (dstformater == null | |   ". Equals (Dstformater))                 return null;            if  (dsttimezoneid == null | |   ". Equals (Dsttimezoneid))                 return null;            SimpleDateFormat sdf = new  SimpleDateFormat (Srcformater);            try {                inT difftime = getdifftimezonerawoffset (Dsttimezoneid);                Date d =  Sdf.parse (Srcdatetime);                long nowtime =  d.gettime ();                long newNowTime  = nowtime - difftime;                d = new  Date (Newnowtime);                return date2string ( DSTFORMATER,&NBSP;D);            } catch  (parseexception e)  {                log.output (e.toString (), &NBSP;LOG.STD_ERR);                return null;            } finally {                sdf = null;           &nbsp}        }           /**        *  Get the system's current default time zone versus UTC. (unit: MS)        *         *  @return   The system's current default time zone versus UTC. (unit: MS)        */       private static int  getdefaulttimezonerawoffset ()  {           return  timezone.getdefault (). Getrawoffset ();       &nbsp           /**         *  gets the difference between the specified time zone and UTC. (unit: MS)        *         *  @param   TimeZoneID        *              time zone ID        *  @return   Specifies the time difference between the timezone and UTC. (unit: MS)        */   &n

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.