java换算当地时间_Java UTC时间与本地时间互相转换

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

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

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

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

package com.summergao.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 SummerGao

* @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 SummerGao

* @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));

}

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值