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