解释: UTC + 时区差 = 本地时间
UTC转成北京时间(本地时间):
/**
* utc时间转成local时间
* @param utcTime
* @return
*/
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;
}
北京时间转成UTC:
/**
* local时间转换成UTC时间
* @param localTime
* @return
*/
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;
}
UTC转成本地时间戳:
/**
* utc时间转成local时间戳
* @param utcTime
* @return
*/
public static Long utcToLocalLong(String utcTime){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
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();
}
long time = locatlDate.getTime()/1000;
return time;
}