如何在 Java 中将 ZonedDateTime 转换为 milliSecond?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/55645505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:13:04  来源:igfitidea点击:

How to convert ZonedDateTime to milliSecond in Java?

javaepochzoneddatetime

提问by Arun

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"). If I convert this to ZonedDateTimewith Zone id ("Asia/Kolkata") then I'm getting ("2019-04-10T05:30+05:30[Asia/Kolkata]"). Then I convert to EpochMilli (1554854400000) = ("Wed Apr 10 2019 00:00:00") in UTC.

让我们说LocalDateTime("2019-04-10T05:30")。如果我将其转换为ZonedDateTimeZone id ("Asia/Kolkata") 那么我得到 ( "2019-04-10T05:30+05:30[Asia/Kolkata]")。然后我"Wed Apr 10 2019 00:00:00"在UTC转换为EpochMilli (1554854400000) = ( ) 。

采纳答案by AxelH

You are using an Instantto get that milliseconds representation. Instant are not zone based. Now, the epoch time is based on the "1970-01-01T00:00:00Z" so you should not have the zone in it.

您正在使用 anInstant来获取毫秒表示。Instant 不是基于区域的。现在,纪元时间基于“1970-01-01T00:00:00Z”,因此您不应该在其中包含该区域。

If you want to create a ZoneDateTimefrom the epoch value, you can simply create an Instantat that epoch time and then create a ZonedDateTimewith 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-12T08:40:31.016+05:30[Asia/Kolkata]

2019-04-12T05:10:31.016+02:00[欧洲/巴黎]
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 LocalDateTimethen a ZonedDateTimeto finally create an Instant. This is just to show that even with a zone, this will be "lost" at one point.
Simply use :

注意:上面的代码不应该这样使用,没有必要得到一个LocalDateTimethen aZonedDateTime来最终创建一个Instant. 这只是为了表明即使有一个区域,它也会在某一时刻“丢失”。
只需使用:

long e = Instant.now().toEpochMilli();