如何从LocalDate和LocalDateTime中提取纪元? [英] How to extract epoch from LocalDate and LocalDateTime?
问题描述
如何从 LocalDateTime
或 LocalDate的实例中将纪元值提取到
?我已尝试以下 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
我想要的只是值 1391539861
表示本地日期时间04.02.2014 19:51:01
。
我的时区是欧洲/奥斯陆
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.
推荐答案
类 LocalDate
和 LocalDateTime
不包含有关 timezone 或时间偏移,以及因为没有此信息,因为纪元将是不确定的。但是,对象有几种方法可以通过传递 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
LocalDate date = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = date.atStartOfDay(zoneId).toEpochSecond();
LocalDateTime
LocalDateTime time = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = time.atZone(zoneId).toEpochSecond();
这篇关于如何从LocalDate和LocalDateTime中提取纪元?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!