如何从 LocalDate 和 LocalDateTime 中提取纪元? [英] How to extract epoch from LocalDate and LocalDateTime?

查看:16
本文介绍了如何从 LocalDate 和 LocalDateTime 中提取纪元?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 LocalDateTimeLocalDate 的实例中提取到 Long 的纪元值?我试过了以下,但它给了我其他结果:

How do I extract the epoch value to Long from instances of LocalDateTime or LocalDate? I've tried the following, but it gives me other results:

LocalDateTime time = LocalDateTime.parse("04.02.2014  19:51:01", DateTimeFormatter.ofPattern("dd.MM.yyyy  HH:mm:ss"));
System.out.println(time.getLong(ChronoField.SECOND_OF_DAY)); // gives 71461
System.out.println(time.getLong(ChronoField.EPOCH_DAY)); // gives 16105

我想要的只是本地日期时间 "04.02.2014 19:51:01" 的值 1391539861.我的时区是 Europe/Oslo UTC+1 夏令时.

What I want is simply the value 1391539861 for the local datetime "04.02.2014 19:51:01". My timezone is Europe/Oslo UTC+1 with daylight saving time.

推荐答案

LocalDateLocalDateTime 类不包含有关时区的信息或时间偏移,如果没有这些信息,自 epoch 以来的秒数将是不明确的.但是,这些对象有多种方法可以通过传递 ZoneId 实例将它们转换为带时区的日期/时间对象.

The classes LocalDate and LocalDateTime do not contain information about the timezone or time offset, and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId instance.

本地日期

LocalDate date = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = date.atStartOfDay(zoneId).toEpochSecond();

本地日期时间

LocalDateTime time = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = time.atZone(zoneId).toEpochSecond();

这篇关于如何从 LocalDate 和 LocalDateTime 中提取纪元?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆