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

2024-07-31 10:26:45 浏览数 (2)

方法1

代码语言:java复制
/**
 * 当前时区时间 → 目标时区时间
 */
public static Date dateFromCurrentToTargetZone(Date date, ZoneId targetZoneId) {
    // 获取对应时区的ZonedDateTime
    ZonedDateTime zonedDateTime = date.toInstant().atZone(targetZoneId);
    // 这一步就是式转换: ZonedDateTime → Date
    return Date.from(zonedDateTime.toLocalDateTime().toInstant(ZonedDateTime.now().getOffset()));
}

方法2

代码语言:java复制
/**
 * 当前时区时间 → 目标时区时间
 */
public static Date dateFromCurrentToTargetZone2(Date date, ZoneId targetZoneId) {
    LocalDateTime localDateTime = date.toInstant().atZone(targetZoneId).toLocalDateTime();
    return new Date(Timestamp.valueOf(localDateTime).getTime());
}

UT测试验证

代码语言:java复制
@Test
public void convertDateFromCurrentToTargetTimeZone_8() throws ParseException {
    Date date = new Date(1562501898000L); // Sun Jul 07 20:18:18 CST 2019
    Date targetDate = MyDateUtil.dateFromCurrentToTargetZone(date, ZoneId.of(" 08:00"));
    Date targetDate2 = MyDateUtil.dateFromCurrentToTargetZone2(date, ZoneId.of(" 08:00"));
    Date expected = DateUtils.parseDate("2019-7-07 20:18:18", "yyyy-MM-dd HH:mm:ss");
    Assert.assertEquals(expected, targetDate);
    Assert.assertEquals(expected, targetDate2);
}
@Test
public void convertDateFromCurrentToTargetTimeZone_9() throws ParseException {
    Date date = new Date(1562501898000L); // Sun Jul 07 20:18:18 CST 2019
    Date targetDate = MyDateUtil.dateFromCurrentToTargetZone(date, ZoneId.of(" 09:00"));
    Date targetDate2 = MyDateUtil.dateFromCurrentToTargetZone2(date, ZoneId.of(" 09:00"));
    Date expected = DateUtils.parseDate("2019-7-07 21:18:18", "yyyy-MM-dd HH:mm:ss");
    Assert.assertEquals(expected, targetDate);
    Assert.assertEquals(expected, targetDate2);
}
@Test
public void convertDateFromCurrentToTargetTimeZone_0() throws ParseException {
    Date date = new Date(1562501898000L); // Sun Jul 07 20:18:18 CST 2019
    Date targetDate = MyDateUtil.dateFromCurrentToTargetZone(date, ZoneId.of(" 00:00"));
    Date targetDate2 = MyDateUtil.dateFromCurrentToTargetZone2(date, ZoneId.of(" 00:00"));
    Date expected = DateUtils.parseDate("2019-7-07 12:18:18", "yyyy-MM-dd HH:mm:ss");
    Assert.assertEquals(expected, targetDate);
    Assert.assertEquals(expected, targetDate2);
}
@Test
public void convertDateFromCurrentToTargetTimeZone_0_1() throws ParseException {
    Date date = new Date(1562501898000L); // Sun Jul 07 20:18:18 CST 2019
    Date targetDate = MyDateUtil.dateFromCurrentToTargetZone(date, ZoneId.of("-01:00"));
    Date targetDate2 = MyDateUtil.dateFromCurrentToTargetZone2(date, ZoneId.of("-01:00"));
    Date expected = DateUtils.parseDate("2019-7-07 11:18:18", "yyyy-MM-dd HH:mm:ss");
    Assert.assertEquals(expected, targetDate);
    Assert.assertEquals(expected, targetDate2);
}

0 人点赞