带有 ZoneOffset 的 IST(印度标准时间)的 LocalDateTime 以更简洁的方式

LocalDateTime for IST(Indian Standard Time) with ZoneOffset in cleaner way

private static int gmtOffet = 19800;

public long convertToLong(LocalDateTime localDateTime) {
    return localDateTime.toInstant(ZoneOffset.ofTotalSeconds(gmtOffet)).toEpochMilli();
}

我在这里明确计算了区域偏移偏移量,对于印度来说是 5h30m。然后转换为秒,用于获取以毫秒为单位的本地时间。 有没有更好的方法来做到这一点,我不必计算时间偏移量,但一些枚举等会选择偏移量?

Instant 一开始就不合适,真的。秒(例如,只是时钟的秒位,去掉了分钟等)是人类时间的概念。 Instant 用于计算机时间,LocalDateZonedDateTime 等用于人类的疯狂恶作剧,包括时区、闰年、闰秒、俄罗斯革命和日历,完全与天文学无关且毫无根据周等概念。人类要疯狂!

ZoneId INDIA_ZONE = ZoneId.of("Asia/Kolkata");
ZonedDateTime zdt = yourLDT.atZone(INDIA_ZONE);
int seconds = zdt.getSecond();

等等。

如果您需要自纪元以来的毫秒数,最实用的方法是像您一样从 Instant 中获取它们。

关于偏移量,从库中获取它更干净、更好:

private static final ZoneId zone = ZoneId.of("Asia/Kolkata");

public long convertToLong(LocalDateTime localDateTime) {
    return localDateTime.atZone(zone).toInstant().toEpochMilli();
}

这传达了您使用当前偏移量的原因。它也是历史日期(印度并不总是使用偏移量+05:30)和未来日期的证据,以防印度政客在未来某个时间决定不同的偏移量。

您可能会再次问自己是否真的需要那个毫秒值?这是低级的。最好将一个时刻表示为 Instant 对象或其他日期和时间对象。当然,如果是你无法控制的遗产API,你别无选择。