A summary of the use of date and time zones in Android

Source: Internet
Author: User
Tags dateformat time zones

In the process of developing Android, there have been several times due to date and time problems, and mainly due to the time zone, so I have been trying to summarize, to form a good development norms.

  A, Unix timestamp   UNIX timestamp (Unix timestamp), or Unix time, or POSIX time, is a time representation method, Defined as the total number of seconds from GMT January 01, 1970 00:00 00 seconds to now. Unix timestamps are used not only in UNIX systems, Unix-like systems, but also in many other operating systems.   II, about time standards and time zones   1, Atoms: International Atomic Time (IAT)   also known as international Atoms, is an atomic clock to get the standard of the Times, atomic clocks are the world's most accurate time measurement and frequency standards, The atomic clock's error in 3.7 billion years does not exceed 1 seconds.   2, World time: Universal time (UT)   is a flat sun starting from Greenwich, Midnight. The world is based on the Earth's rotation as the benchmark to get the time scale, the accuracy of the Earth's rotation uneven change and the impact of the polar shift, in order to resolve this effect, the 1955 International Astronomical Union defined the UT0, UT1 and UT2 three systems, they are progressive relationship between the three, the latter is to find some of the former measurement differences, A more uniform time mark is obtained by correcting.   in the Greenwich Meridian when the Sun is called the World (UT0), also known as Greenwich Normal (GMT). Greenwich Mean Time (old-time GMT or GMT, English: Greenwich Mean time,gmt) refers to the standard time of the Royal Greenwich Observatory, located in the outskirts of London, as the Prime meridian is defined through the meridians there. Since February 5, 1924, the Greenwich Observatory has been distributing information to the world on an hourly interval.   2. Coordinated world time: coordinated Universal time (UTC)   also known as World standard Time, world unification times. It is a time when the average solar time (GMT), the new time scale after the axis movement has been revised, and the international atom with the "second" unit, the computational process is quite rigorous and precise, so UTC is more accurate than GMT in terms of "world standard Time". Its error value must be kept within 0.9 seconds, if greater than 0.9 seconds by the International Earth Rotation Transaction Central Bureau in Paris to release a leap second, so that UTC and the Earth's rotation period is consistent.   Basically the nature of UTC emphasizes a more accurate world time standard than GMT, with one more leap second adjustment in UTC to ensure Coordinated Universal Time (UTC) and Greenwich Mean (GMT) does not exceed 0.9 seconds, and adds positive or negative leap seconds in Coordinated Universal Time (UTC) when necessary.   UTC is used in most computers and network standards.   3, daylight saving time and winter: Daylight Saving Time (DST)   also known as daylight saving time and daylight saving time, is a system for saving energy, which is used by people to set local times, which is called "Daylight savings" during the implementation of the system. Usually early in the morning of the summer for an hour ahead of time, can make people early to sleep early, reduce the amount of lighting, to make full use of light resources, thereby saving lighting electricity. Each country that adopts daylight saving time is specified differently. At present, nearly 110 countries around the world have to implement daylight saving time every year. Since March 27, 2011, Russia has been permanently using daylight saving time, which has been set aside for an hour and no longer recalled.   In a nutshell, use daylight saving time and winter time to dial up to one hours in the summer, and wait until winter to slow down one hours.       4, cst  CST also represents Australia, the United States, China, Cuba, four countries of the standard time, the time zone is:  Australia, Central Time (Australia) ut+9:30 Chubu Standard Time zone (North America), America ut-6:00 Beijing time, China standard Time ut+8:00 IME ut-4:00  in development we need to be aware of the time zones of different countries, and the use of UTC and GMT in computer systems is not significantly different and can be considered equivalent.   Two, specification   in the actual development, when the time for display, non-special requirements generally use the system default time zone times as the display time. When you store time as data or pass it to other systems, especially cross-platform calls, it is best to use the standard UTC/GMT time (hereafter referred to as GMT), unless you have previously contracted or identified the type of time.   Three, the need for special attention in Android   1, the type of date and time in Android, there are date, Calendar, they are not shown when setting their time zone, the current time is the system default time zone, even given a time, The same time is converted by the system's default time zone, so they are all associated with time zones.   2, the SimpleDateFormat object itself is also associated with the time zone. &nbSp When using parse to convert a date in a string format to a Date object, or to convert a Date object to a string date, the time zone of the string date is subject to the SimpleDateFormat associated time zone, and if the time zone is modified by Settimezone, This string date is based on the modified time zone. For example:  //2013-1-31 22:17:14date date = new Date (1359641834000L); SYSTEM.OUT.PRINTLN (date); String datestr = "2013-1-31 22:17:14"; SimpleDateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");d Ateformat.settimezone ( Timezone.gettimezone ("GMT"));try{   //For DateFormat that have been set to GMT time standard, all the string dates that need to be converted are GMT standard times, The date returned after conversion is due to default to the system default time zone, so the day converted to date requires +8 (for example, the Beijing Standard Time zone), which is the difference between time zones and standards.     Date datetmp = Dateformat.parse (datestr);    System.out.println (datetmp);}  catch (parseexception e)  {    e.printstacktrace ();  }  //date or by system default time zone. The string that is formatted at format is GMT, so 8. String datestrtmp = Dateformat.format (date);     system.out.println (DATESTRTMP); The output is: Image 3, calendar is related to the system default time zone when the time zone is not set manually. After you manually modify the time zone, you cannot use the Calendar.gettime method to get the date day directly, because the date is the same as the value at SetTime, and you want to get the time after the time zone is modified correctly, you should pass the calendar get method. Example:  date Date = new Date (1359641834000L); SYSTEM.OUT.PRINTLN (date); Calendar calendar = Calendar.getinstance (); Calendar.settimezone (Timezone.gettimezone ("GMT"));  //or can calendar calendar = calendar.getinstance (Timezone.gettimezone ("GMT"));  calendar.settime (date); System.out.println (Calendar.get (Calendar.hour_of_day) + ":" + calendar.get (Calendar.minute));  calendar CALENDAR2 = Calendar.getinstance ();  calendar2.set (Calendar.get (calendar.year), Calendar.get (Calendar.month), Calendar.get (Calendar.DAY_OF_ MONTH), Calendar.get (Calendar.hour_of_day), Calendar.get (Calendar.minute), Calendar.get (Calendar.second));  System.out.println (Calendar.gettime ());     system.out.println (Calendar2.gettime ()); The input result is:image  4, timezone  in development, we can get detailed information about the system default time zone and its related by TimeZone object.   Android about Date tool class  /** * Copyright (C), bhj * All rights reserved. *  * file name: & nbsp;* file ID:  * file Summary:  *  * current version:  * for    :  * Finish DayPeriod: 2013-12-20 *  * superseded version:  * modified:  * Modified by:  * Modification Summary:  */ package com.bhj.timetest;  import Java.text.parseexception;import Java.text.simpledateformat;import Java.util.Calendar;import Java.util.date;import java.util.timezone; /** * Date Tool class (not specifically described in the system default time zone)  * */public class dateutil{       /** 1s==1000ms */    private final static int time_milliseconds = 1000;    /** time in minutes and seconds Max is */    private final static int time_numbers = 60;   /** time hour maximum */    Private final static int time_hourses = 24;   /** formatted date standard string */    private final static string FORMA T = "Yyyy-mm-dd HH:mm:ss";       /**     * get time zone information      * */  & nbsp public static TimeZone getTimeZone ()     {        return Timezone.getdefault ();    }       /**  &NBsp  * Convert date string to date object      * @param a date date string, must be "Yyyy-mm-dd HH:mm:ss"      * @return Date character Date object expression for string      * */    public static date Parsedate (string date)     {    &N Bsp   Return parsedate (date, FORMAT);   }       /**     * convert date string to D Ate object      * @param date string, must be "Yyyy-mm-dd HH:mm:ss"      * @param format format string   &NBS P  * Date Object representation of a @return dates string      * */    public static date Parsedate (string date, string for MAT)     {        Date dt = null;        SimpleDateFormat DateFormat = NE W SimpleDateFormat (format);        try        {            DT = dateformat.parse (date);       }        catch (parseexception e)         {            e.printstacktrace ();       }      & nbsp;         return dt;   }       /**     * Converts a Date object to a string of the specified format      * @param the date Date object      * @return The string representation of the Date object Yyyy-mm-dd hh:mm: SS "     * */    public static String formatdate (date date)     {      &NB Sp return FormatDate (date, FORMAT);     }       /**     * Convert a Date object to a string in the specified format      * @p Aram Date Date Object      * @param string format format string      * @return Date object in the form of strings      * */    public static string FormatDate (date date, String format)     {      &NBS P SimpleDateFormat DateFormat = new SimpleDateFormat (format);          return DateformAt.format (date);     }    /**     * formatted date      * @param long unixtime Unix Timestamp & nbsp    * @return Date string "Yyyy-mm-dd HH:mm:ss"      * */    public static string Formatunixtime (Long Unixtime)     {         return Formatunixtime (Unixtime, FORMAT);   }&N Bsp      /**     * formatted date      * @param long unixtime Unix timestamp     &N bsp;* @param string Format formatted string      * @return Date string      * */    public static St Ring Formatunixtime (Long unixtime, String format)     {        SimpleDateFormat DateFormat = New SimpleDateFormat (format);          return Dateformat.format (unixtime);     }       /**     * Date string representation of the GMT date format to the system default time zone     & nbsp;* @param GmtuniXtime GTM timestamp      * @return Date string "Yyyy-mm-dd HH:mm:ss"      * */    public static St Ring Formatgmtunixtime (Long gmtunixtime)     {        return Formatgmtunixtime (gmtunixtime , format);    }       /**     * format GMT as a date string representation of the system default time zone      * @param gmtunixtime gtm timestamp      * @param format formatted string      * @return Date Word String "Yyyy-mm-dd HH:mm:ss"      * */    public static string Formatgmtunixtime (long gmtunixtime, Str ing format)     {        SimpleDateFormat DateFormat = new SimpleDateFormat (format);  &N Bsp     Return Dateformat.format (Gmtunixtime + timezone.getdefault (). Getrawoffset ());    }        /**     * Get date representation of timestamp      * @param unixtime Unix timestamp &nbs P    * @return Date Object   &NBsp  * */    public static Date getDate (long unixtime)     {         return New Date (Unixtime);     }       /**     * Gets the date representation of the GMT timestamp (converted to the date representation, Time in the system default time zone)      * @param gmtunixtime GMT unix timestamp      * @return Date object      * */    public static date getgmtdate (long gmtunixtime)     {        return new Date ( Gmtunixtime + Timezone.getdefault (). Getrawoffset ());    }    /**     * Convert the UNIX timestamp of the system default time zone to GMT Unix timestamp      * @param unixtime Unix timestamp      * @return GMT Unix timestamp      * */    public static long Getgmtunixtime (long unixtime)     {        Return Unixtime-timezone.getdefault (). Getrawoffset ();   }    /**     * will GMT U Nix timestamp converted to the system default time zoneUnix timestamp      * @param gmtunixtime GMT unix timestamp      * @return system default time zone Unix timestamp     &NBSP ; * */    public static long Getcurrenttimezoneunixtime (long gmtunixtime)     {      &NBS P return gmtunixtime + Timezone.getdefault (). Getrawoffset ();   }       /**  & nbsp  * gets the current time of the GMT Unix timestamp      * @return current GMT Unix timestamp      * */    public static Long Getgmtunixtimebycalendar ()     {        Calendar calendar = Calendar.getinstance (); nbsp      //Get time stamp for datetime under current time zone         Long unixtime = Calendar.gettimeinmillis ();  &NB Sp    //Get the time stamp for the standard GMT time of day          Long unixtimegmt = Unixtime-timezone.getdefault ( ). Getrawoffset ();        return unixtimegmt;   }       /**      * Gets the current time of the Unix timestamp      * @return Current UNIX timestamp      * */    public static long Getunixtim Ebycalendar ()     {        Calendar calendar = calendar.getinstance ();      &N Bsp Get time stamp for date time in current time zone         Long unixtime = Calendar.gettimeinmillis ();        RET Urn unixtime;   }       /**      * get time zone after change       * @param date time       * @param oldzone old zone       * @param newzone new time zone & nbsp;     * @return time      */     public static date changetimezone (Date dat E, TimeZone Oldzone, TimeZone newzone)      {         Date datetmp = null;  & nbsp     if (date! = null)         {            int timeoffset = old Zone.getrawoffset ()-Newzone.getrawoffset ();            datetmp = new Date (Date.gettime ()-Timeoffset);       }        return datetmp;   }       /**    &NBSP;* Converts the total number of seconds to the last minute expression      * @param seconds any number of seconds      * @return%s hours%s minutes%s seconds   &nbs P  */    public static String Formattime (long seconds)     {        long hh = se conds/time_numbers/time_numbers;        long mm = (SECONDS-HH * time_numbers * time_numbers) ; 2} (SECONDS-HH * time_numbers * time_numbers)/time_numbers:0;        Long ss = seconds < Time_nu Mbers? Seconds:seconds% time_numbers;        return     (hh = = 0?) "": (HH < 10? ") 0 "+ hh:hh) +" hours ")                  + (mm = = 0?) "": (mm < 10?) 0 "+ mm:mm) +" min ")                  + (ss = = 0?) "": (SS < 10? ") 0 "+ ss:ss) +" seconds ");   }       /**     * get the approximate expression of the current time distance from the specified date      * @param long date      * approximate expression of @return time difference      * */    Public stat IC string getdifftime (long date)     {        String strtime = "Long time ago";        Long time = Math.Abs (new Date (). GetTime ()-date);       //Less than one minute         I F (Time < Time_numbers * Time_milliseconds)         {            Strtim E = "just";       }        else        {      &N Bsp     int min = (int) (time/time_milliseconds/time_numbers);            if (min &l T Time_numbers)         &NBSP   {                if (min <)             & nbsp   {                    Strtime = "Quarter hour ago";               }                Else if (min <)     &N Bsp           {                    Strtime = "half an hour ago" ;               }                ELSE&NBS P               {                    St Rtime = "1 hours ago";               }           }            else            {          &NBSP ;     int hh = min/time_numbers;                if (HH < time_hourses)                 {                    St Rtime = hh + "Hour ago";               }            &NBS P   else                {              &NBSP ;     int days = hh/time_hourses;                    if (Days & lt;= 6)                     {            &N Bsp           Strtime = days + "day before";                  &N Bsp }                    else            &NBSP ;       {                        int weeks = DAYS/7;&N Bsp                       if (weeks < 3)         & nbsp               {                    &N Bsp       Strtime = weeks + "weeks ago";                           }      &NB Sp            }               }      & nbsp    }       }                return STRTIME;&N Bsp  }}

Summary of Use of datetime and time zone in Android

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.