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

协调世界时,又称世界统一时间、世界标准时间、国际协调时间。由于英文(CUT)和法文(TUC)的缩写不同,作为妥协,简称UTC。
这套时间系统被应用于许多互联网和万维网的标准中,例如,网络时间协议就是协调世界时在互联网中使用的一种方式。
在军事中,协调世界时区会使用“Z”来表示。又由于Z在无线电联络中使用“Zulu”作代称,协调世界时也会被称为"Zulu time"。
中国大陆、中国香港、中国澳门、中国台湾、蒙古国、新加坡、马来西亚、菲律宾、西澳大利亚州的时间与UTC的时差均为+8,也就是UTC+8。

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 {

/**
 * 
 * <p>Description: 本地时间转化为UTC时间</p>
 * @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;
}

/**
 * 
 * <p>Description:UTC时间转化为本地时间 </p>
 * @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));
}

}

欢迎加群交流,QQ群:66728073,197321069,398808948 更多文章:http://www.coc88.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wgslucky

各位都是我的衣食父母

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值