Java UTC时间与本地时间互相转换 您所在的位置:网站首页 java中dategettime Java UTC时间与本地时间互相转换

Java UTC时间与本地时间互相转换

#Java UTC时间与本地时间互相转换| 来源: 网络整理| 查看: 265

协调世界时,又称世界统一时间、世界标准时间、国际协调时间。由于英文(CUT)和法文(TUC)的缩写不同,作为妥协,简称UTC。

这套时间系统被应用于许多互联网和万维网的标准中,例如,网络时间协议就是协调世界时在互联网中使用的一种方式。

在军事中,协调世界时区会使用“Z”来表示。又由于Z在无线电联络中使用“Zulu”作代称,协调世界时也会被称为"Zulu time"。

中国大陆、中国香港、中国澳门、中国台湾、蒙古国、新加坡、马来西亚、菲律宾、西澳大利亚州的时间与UTC的时差均为+8,也就是UTC+8。

--javascripttypescriptbashsqljsonhtmlcssccppjavarubypythongorustmarkdown

package com.xinyue.interview.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class DateUtil { /** * *

Description: 本地时间转化为UTC时间

* @param localTime * @return * @author wgs * @date 2018年10月19日 下午2:23:43 * */ public static Date localToUTC(String localTime) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date localDate= null; try { localDate = sdf.parse(localTime); } catch (ParseException e) { e.printStackTrace(); } long localTimeInMillis=localDate.getTime(); /** long时间转换成Calendar */ Calendar calendar= Calendar.getInstance(); calendar.setTimeInMillis(localTimeInMillis); /** 取得时间偏移量 */ int zoneOffset = calendar.get(java.util.Calendar.ZONE_OFFSET); /** 取得夏令时差 */ int dstOffset = calendar.get(java.util.Calendar.DST_OFFSET); /** 从本地时间里扣除这些差量,即可以取得UTC时间*/ calendar.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset)); /** 取得的时间就是UTC标准时间 */ Date utcDate=new Date(calendar.getTimeInMillis()); return utcDate; } /** * *

Description:UTC时间转化为本地时间

* @param utcTime * @return * @author wgs * @date 2018年10月19日 下午2:23:24 * */ public static Date utcToLocal(String utcTime){ SimpleDateFormat sdf = new SimpleDateFormat("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(); } return locatlDate; } public static void main(String[] args) { String time = "2018-10-19 04:23:34"; System.out.println(DateUtil.utcToLocal(time)); } }

原文地址 : https://www.cnblogs.com/wgslucky/p/9816259.html



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有