[英]How to convert ZonedDateTime to milliSecond in Java?
I'm trying to convert ZonedDateTime to milliseconds using below code.我正在尝试使用以下代码将 ZonedDateTime 转换为毫秒。
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zonedDateTime =ldt.atZone(ZoneId.of(""Asia/Kolkata""));
zonedDateTime.toInstant().toEpochMilli();
But this one returns milliseconds based on local time.但是这个基于本地时间返回毫秒。 And it's not considering ZoneId.而且它没有考虑 ZoneId。
Let's say LocalDateTime("2019-04-10T05:30")
.假设LocalDateTime("2019-04-10T05:30")
。 If I convert this to ZonedDateTime
with Zone id ("Asia/Kolkata") then I'm getting ( "2019-04-10T05:30+05:30[Asia/Kolkata]"
).如果我将其转换为具有区域 ID ("Asia/Kolkata") 的ZonedDateTime
,那么我将得到 ( "2019-04-10T05:30+05:30[Asia/Kolkata]"
)。 Then I convert to EpochMilli (1554854400000) = ( "Wed Apr 10 2019 00:00:00"
) in UTC.然后我在 UTC 中转换为 EpochMilli (1554854400000) = ( "Wed Apr 10 2019 00:00:00"
)。
You are using an Instant
to get that milliseconds representation.您正在使用Instant
来获取该毫秒表示。 Instant are not zone based. Instant 不是基于区域的。 Now, the epoch time is based on the "1970-01-01T00:00:00Z" so you should not have the zone in it.现在,纪元时间基于“1970-01-01T00:00:00Z”,因此您不应该在其中包含区域。
If you want to create a ZoneDateTime
from the epoch value, you can simply create an Instant
at that epoch time and then create a ZonedDateTime
with the zone you wish:如果你想从纪元值创建一个ZoneDateTime
,你可以简单地在那个纪元时间创建一个Instant
,然后用你想要的区域创建一个ZonedDateTime
:
//Let's create our zone time (just to keep your logic
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zonedDateTime =ldt.atZone(ZoneId.of("Asia/Kolkata"));
//Then get the epoch on GMT
long e = zonedDateTime.toInstant().toEpochMilli();
Instant i = Instant.ofEpochMilli(e);
System.out.println(ZonedDateTime.ofInstant(i, ZoneId.systemDefault()));
System.out.println(ZonedDateTime.ofInstant(i, ZoneId.of("Asia/Kolkata")));
2019-04-12T05:10:31.016+02:00[Europe/Paris] 2019-04-12T05:10:31.016+02:00[欧洲/巴黎]
2019-04-12T08:40:31.016+05:30[Asia/Kolkata] 2019-04-12T08:40:31.016+05:30[亚洲/加尔各答]
NOTE: The code above should not be used like this, it is not necessary to get a LocalDateTime
then a ZonedDateTime
to finally create an Instant
.注意:上面的代码不应该这样使用,没有必要先获取LocalDateTime
然后再获取ZonedDateTime
来最终创建Instant
。 This is just to show that even with a zone, this will be "lost" at one point.这只是为了表明即使有一个区域,这也会在某一时刻“丢失”。
Simply use:只需使用:
long e = Instant.now().toEpochMilli();
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zonedDateTime =ldt.atZone(ZoneId.of("UTC"));
zonedDateTime.toInstant().toEpochMilli();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.