目标时区时间 转换为 当前时区时间

2024-07-31 10:44:18 浏览数 (1)

方法1

代码语言:java复制
/**
 * 目标时区时间 → 当前时区时间
 */
public static Date dateFromTargetToCurrentZone(Date date, ZoneId targetZoneId) {
    // 这一步就是式转换: Date → ZonedDateTime
    ZonedDateTime targetZonedDateTime = date.toInstant().atZone(ZonedDateTime.now().getZone());
    
    // 目标时区ZonedDateTime → 当前时区ZonedDateTime
    ZonedDateTime currentZonedDateTime = ZonedDateTime.ofInstant(targetZonedDateTime.toLocalDateTime().toInstant((ZoneOffset) targetZoneId), ZoneId.systemDefault());
    
    // 这一步就是式转换: ZonedDateTime → Date
    return Date.from(currentZonedDateTime.toLocalDateTime().toInstant(ZonedDateTime.now().getOffset()));
}

方法2

代码语言:java复制
/**
 * 目标时区时间 → 当前时区时间
 */
public static Date dateFromTargetToCurrentZone2(Date date, ZoneId targetZoneId) {
    // 为了获取没有时区的时间
    LocalDateTime localDateTime = date.toInstant().atZone(ZonedDateTime.now().getZone()).toLocalDateTime();
    
    // localDateTime视为targetZone的localDateTime → 前时区时间
    return Date.from(localDateTime.toInstant((ZoneOffset) targetZoneId));
}

UT测试验证

代码语言:java复制
@Test
public void convertDateFromTargetToCurrentTimeZone_9() throws ParseException {
    Date date = new Date(1562501898000L); // Sun Jul 07 20:18:18 CST 2019
    Date targetDate = MyDateUtil.dateFromTargetToCurrentZone(date, ZoneId.of(" 09:00"));
    Date targetDate2 = MyDateUtil.dateFromTargetToCurrentZone2(date, ZoneId.of(" 09:00"));
    Date expected = DateUtils.parseDate("2019-7-07 19:18:18", "yyyy-MM-dd HH:mm:ss");
    Assert.assertEquals(expected, targetDate);
    Assert.assertEquals(expected, targetDate2);
}
@Test
public void convertDateFromTargetToCurrentTimeZone_0() throws ParseException {
    Date date = new Date(1562501898000L); // Sun Jul 07 20:18:18 CST 2019
    Date targetDate = MyDateUtil.dateFromTargetToCurrentZone(date, ZoneId.of(" 00:00"));
    Date targetDate2 = MyDateUtil.dateFromTargetToCurrentZone2(date, ZoneId.of(" 00:00"));
    Date expected = DateUtils.parseDate("2019-7-08 04:18:18", "yyyy-MM-dd HH:mm:ss");
    Assert.assertEquals(expected, targetDate);
    Assert.assertEquals(expected, targetDate2);
}
@Test
public void convertDateFromTargetToCurrentTimeZone_0_1() throws ParseException {
    Date date = new Date(1562501898000L); // Sun Jul 07 20:18:18 CST 2019
    Date targetDate = MyDateUtil.dateFromTargetToCurrentZone(date, ZoneId.of("-01:00"));
    Date targetDate2 = MyDateUtil.dateFromTargetToCurrentZone2(date, ZoneId.of("-01:00"));
    Date expected = DateUtils.parseDate("2019-7-08 05:18:18", "yyyy-MM-dd HH:mm:ss");
    Assert.assertEquals(expected, targetDate);
    Assert.assertEquals(expected, targetDate2);
}

0 人点赞