Java UTC time and local time are converted to each other

Source: Internet
Author: User
Tags local time

1, local time to UTC time

    /*** local time converted to UTC time *@paramlocaltime *@return     */     Public StaticDate LOCALTOUTC (String localtime) {SimpleDateFormat SDF=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Date localdate=NULL; Try{localdate=Sdf.parse (localtime); } Catch(ParseException e) {e.printstacktrace (); }        Longlocaltimeinmillis=Localdate.gettime (); /**long time converted to calendar*/Calendar Calendar=calendar.getinstance ();        Calendar.settimeinmillis (Localtimeinmillis); /**Get time offset*/        intZoneoffset =Calendar.get (Java.util.Calendar.ZONE_OFFSET); /**Get Daylight Saving time difference*/        intDstoffset =Calendar.get (Java.util.Calendar.DST_OFFSET); /**subtract these differences from local time, which means you can get UTC time*/Calendar.add (Java.util.Calendar.MILLISECOND,-(Zoneoffset +dstoffset)); /**the time obtained is UTC standard Time*/Date utcdate=NewDate (Calendar.gettimeinmillis ()); returnutcdate; }

2. UTC time change to local time

    /*** UTC time is converted to local time *@paramUtctime *@return     */     Public StaticDate utctolocal (String utctime) {SimpleDateFormat SDF=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Sdf.settimezone (Timezone.gettimezone ("UTC")); Date utcdate=NULL; Try{utcdate=Sdf.parse (utctime); } Catch(ParseException e) {e.printstacktrace ();        } sdf.settimezone (Timezone.getdefault ()); Date locatldate=NULL; String localtime=Sdf.format (Utcdate.gettime ()); Try{locatldate=Sdf.parse (localtime); } Catch(ParseException e) {e.printstacktrace (); }        returnlocatldate; }

Java UTC time and local time are converted to each other

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.