时间字符串转时区
根据字符串和时间格式,目标时区Id和源时区Id来转换
public static Date convertZoneTimeByString(String sourceDate, String sourceZoneId, String targetZoneId,String pattern) throws ParseException {
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());
}
private static final String PATTERN = "yyyy-MM-dd HH:mm:ss";
public static Date convertZoneTimeByString(String sourceDate, String sourceZoneId, String targetZoneId) throws ParseException {
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());
}
Date类型转时区
Date类型转string 时区转换
public static String convertZoneTimeToString(Date sourceDate, String targetZoneId) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(targetZoneId));
return simpleDateFormat.format(sourceDate);
}
Date和Date进行时区转换
public static Date convertZoneTimeToDate(Date sourceDate, String targetZoneId) throws ParseException {
return Date.from(ZonedDateTime.ofInstant(sourceDate.toInstant(), ZoneId.of(targetZoneId)).toInstant());
}
注:如果是Date类型进行时区转换需要注意Date类型的自身时区,如果是String可以不用考虑自身时区的问题,但是需要额外的源时区字段表示自身时区。