把当前时区时间视为某一时区时间 并将其转换为 目标时区时间

2024-07-31 10:51:08 浏览数 (2)

方式1

代码语言:java复制
/**
 * source时区时间 → target时区时间
 */
public static Date dateFromSourceToTargetZone(Date date, ZoneId sourceZoneId, ZoneId targetZoneId) {
    // 为了获取没有时区的时间
    LocalDateTime localDateTime = date.toInstant().atZone(ZonedDateTime.now().getZone()).toLocalDateTime();
    
    // source时区ZonedDateTime → target时区ZonedDateTime
    ZonedDateTime targetZonedDateTime = ZonedDateTime.ofInstant(localDateTime.toInstant((ZoneOffset) sourceZoneId), targetZoneId);
    
    // 这一步就是格式转换: ZonedDateTime → Date
    return Date.from(targetZonedDateTime.toLocalDateTime().toInstant(ZonedDateTime.now().getOffset()));
}

UT测试验证

代码语言:java复制
@Test
public void dateFromSourceToTargetZone_8to9() throws ParseException {
    Date date = new Date(1562501898000L); // Sun Jul 07 20:18:18 CST 2019
    Date targetDate = MyDateUtil.dateFromSourceToTargetZone(date, ZoneId.of(" 08:00"), ZoneId.of(" 09:00"));
    Date expected = DateUtils.parseDate("2019-7-07 21:18:18", "yyyy-MM-dd HH:mm:ss");
    Assert.assertEquals(expected, targetDate);
}
@Test
public void dateFromSourceToTargetZone_7to9() throws ParseException {
    Date date = new Date(1562501898000L); // Sun Jul 07 20:18:18 CST 2019
    Date targetDate = MyDateUtil.dateFromSourceToTargetZone(date, ZoneId.of(" 07:00"), ZoneId.of(" 09:00"));
    Date expected = DateUtils.parseDate("2019-7-07 22:18:18", "yyyy-MM-dd HH:mm:ss");
    Assert.assertEquals(expected, targetDate);
}
@Test
public void dateFromSourceToTargetZone_01to9() throws ParseException {
    Date date = new Date(1562501898000L); // Sun Jul 07 20:18:18 CST 2019
    Date targetDate = MyDateUtil.dateFromSourceToTargetZone(date, ZoneId.of("-01:00"), ZoneId.of(" 09:00"));
    Date expected = DateUtils.parseDate("2019-7-08 06:18:18", "yyyy-MM-dd HH:mm:ss");
    Assert.assertEquals(expected, targetDate);
}

0 人点赞