public static void main(String[] args) throws Exception {
addZoneOffset("20191226101400");
}
//获取指定时间的 指定时区时间 参照点:默认时区
public LocalDateTime getZoneTime2(LocalDateTime time, ZoneId dest) {
Objects.requireNonNull(dest);
return getZoneTime(time, null, dest);
}
//版本2
public static LocalDateTime getZoneTime(LocalDateTime time,ZoneId src,ZoneId dest) {
//难点就是如何求偏移量
//这里使用默认时区,在中国的就是中国,在美国的就是美国,这样估计更合适
Objects.requireNonNull(dest);
ZonedDateTime z1=null;
if (src==null) {
z1 = time.atZone(ZoneId.systemDefault());
}else{
z1 = time.atZone(src);
}
//
ZonedDateTime z2 = z1.withZoneSameInstant(dest);
//处理重叠问题
long hours = Duration.between(z2.withEarlierOffsetAtOverlap(), z2.withLaterOffsetAtOverlap()).toHours();
z2= z2.plusHours(hours);
getZoneDesc(src);
System.out.println(dest.getId()+"对应得标准时区:"+getZoneDesc(dest));
System.out.println("目标时区"+dest+"的时间"+z2.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
System.out.println("-------------");
return z2.toLocalDateTime();
}
private static String getZoneDesc(ZoneId dest) {
Objects.requireNonNull(dest);
ZoneRules rule=dest.getRules();
//获取时区的标准偏移量
String standardOffset = rule.getStandardOffset(ZonedDateTime.now(dest).toInstant()).getId();
String s = standardOffset.split(":")[0];
int Offset = Integer.parseInt(s);
//返回方式1:带小时分钟
// return "GMT"+standardOffset;
//返回方式2:只带小时数
if (Offset>0) {
return "GMT+"+Offset;
}else{
return "GMT"+Offset;
}
}
/**
* 加上时区偏移
*a
* @param time 传入时间
* @return 加上时区偏移之后的时间
*/
public static String addZoneOffset(String time) throws Exception {
// 获取配置文件中时区偏移的偏移量
long zoneInfoOffset = getZoneOffset();
// 传入时间转换成毫秒
long timeToLong = new SimpleDateFormat("yyyyMMddHHmmss").parse(time).getTime();
// 获取当前容器的时区偏移量
long currOffset = TimeZone.getDefault().getRawOffset();
// 加上用户时区偏移量并减去容器时区偏移(得到用户时区偏移时间)
timeToLong = timeToLong + zoneInfoOffset - currOffset;
// 转换成yyyyMMddHHmmss格式之后返回
Date date = new Date();
date.setTime(timeToLong);
time = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
return time;
}
/**
* 减去时区偏移
*
* @param time 传入时间
* @return 减去时区偏移之后的时间
*/
public static String subZoneOffset(String time) throws Exception {
// 获取配置文件中时区偏移的偏移量
long zoneInfoOffset = getZoneOffset();
// 获取当前容器的时区偏移量
long currOffset = TimeZone.getDefault().getRawOffset();
// 传入时间转换成毫秒
long timeToLong = new SimpleDateFormat("yyyyMMddHHmmss").parse(time).getTime();
// 减去用户时区偏移量并加上容器时区偏移量(得到容器时区偏移时间)
timeToLong = timeToLong - zoneInfoOffset + currOffset;
// 转换成yyyyMMddHHmmss格式之后返回
Date date = new Date();
date.setTime(timeToLong);
time = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
return time;
}
/**
* 获取配置文件中时区偏移的偏移量
* @return 配置文件中时区偏移的偏移量
*/
private static long getZoneOffset() {
// 获取配置文件中的时区偏移配置
TimeZone timeZone = TimeZone.getTimeZone("GMT-6");
timeZone.getDSTSavings();
// 获取配置文件中时区偏移的偏移量
return timeZone.getRawOffset();
}
timeZone处理夏令时
最新推荐文章于 2024-04-16 15:44:56 发布