package com.gzhuiqun.util;
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 UTC标准时间
*/
public static String localToUTC(String localTime) {
/*创建格式化时间对象simpleDateFormat,并初始化格式yyyy-MM-dd HH:mm:ss*/
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 sdf.format(utcDate);
}
/**
* Description:UTC时间转化为本地时间
* @param utcTime
* @return 本地时间
*/
public static String utcToLocal(String utcTime){
/*创建格式化时间对象simpleDateFormat,并初始化格式yyyy-MM-dd HH:mm:ss*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/*创建时区对象utcZone,获取utc所在的时区*/
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 sdf.format(locatlDate);
}
public static void main(String[] args) {
String time = "2019-3-7 14:36:34";
System.out.println(DateUtil.utcToLocal(time));
System.out.println(DateUtil.localToUTC(time));
}
}