Java8中我们常用的时区类是ZoneDateTime,使用ZoneDateTime可以任意转Date的时区来显示,这些转换都是依照标准时间UTC0转时间,所以不同时区显示的时间不一样,可以通过偏移量来计算区分。
但是有一种情况是我们需要是我要转某个时间的时区而不是时间的转换或则显示转换。
如:真正的转时区通常发生在前后端传递时间参数,如果不是时间戳传递,传入后端的通常是默认系统JDK时区,所以如果前端有指定的时区需要后端转换后使用
时区转换代码:
/**
* 时区转换支持字符串时间
* 缺省格式 "yyyy-MM-dd HH:mm:ss"
* @param sourceDate
* @param sourceZoneId
* @param targetZoneId
* @return
* @throws ParseException
*/
public static Date convertZoneTimeByString(String sourceDate, String sourceZoneId, String targetZoneId) {
try {
if (sourceDate == null) {
return null;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(sourceZoneId));
Date date = simpleDateFormat.parse(sourceDate);
return Date.from(ZonedDateTime.ofInstant(date.toInstant(), ZoneId.of(targetZoneId)).toInstant());
} catch (ParseException e) {
log.warn("DateBizUtils convertZoneTimeByString parse date error:{}", sourceDate);
throw new RuntimeException("DateBizUtils convertZoneTimeByString parse date error", e);
}
}
/**
* 时区转换
* 返回时间字符串
* @param sourceDate
* @param targetZoneId
* @return
* @throws ParseException
*/
public static String convertZoneTimeToString(Date sourceDate, String targetZoneId) {
if (sourceDate == null) {
return null;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(targetZoneId));
return simpleDateFormat.format(sourceDate);
}
/**
* date类型时区转换
* @param sourceZoneId
* @param targetZoneId
* @param sourceDate
* @return
*/
public static Date convertTargetTimeZoneDate(String sourceZoneId, String targetZoneId, Date sourceDate){
if(sourceDate == null) {
return null;
}
ZoneId sourceZone;
if(sourceZoneId == null) {
sourceZone = ZoneId.systemDefault();
} else {
sourceZone = ZoneId.of(sourceZoneId);
}
ZoneId targetZone;
if(targetZoneId == null) {
targetZone = ZoneId.systemDefault();
} else {
targetZone = ZoneId.of(targetZoneId);
}
return Date.from(LocalDateTime.ofInstant(sourceDate.toInstant(), targetZone).atZone(sourceZone).toInstant());
}
/**
* patten date without time
* @param date
* @return
*/
public static String convertPattenDate(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN_DATE);
return simpleDateFormat.format(date) + " 00:00:00";
}
注:时区转换如果使用Date类型作为入参和出参,会存在Date类型本身自带或则自动转换服务器时区的问题。