Java 8 - 从 LocalDateTime 和 TimeZone 创建 Instant

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44569202/
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-12 01:36:00  来源:igfitidea点击:

Java 8 – Create Instant from LocalDateTime with TimeZone

javadatejava-8localdate

提问by La Carbonell

I have a date stored in the DB in string format ddMMyyyy and hh:mm and the TimeZone. I want to create an Instant based on that information, but I don't know how to do it.

我有一个日期以字符串格式 ddMMyyyy 和 hh:mm 以及时区存储在数据库中。我想根据该信息创建一个 Instant,但我不知道该怎么做。

something like

就像是

LocalDateTime dateTime = LocalDateTime.of(2017, Month.JUNE, 1, 13, 39);
Instant instant = dateTime.toInstant(TimeZone.getTimeZone("ECT"));

采纳答案by Jorn Vernee

You can first create a ZonedDateTimewith that time zone, and then call toInstant:

您可以先ZonedDateTime使用该时区创建一个,然后调用toInstant

LocalDateTime dateTime = LocalDateTime.of(2017, Month.JUNE, 15, 13, 39);
Instant instant = dateTime.atZone(ZoneId.of("Europe/Paris")).toInstant();
System.out.println(instant); // 2017-06-15T11:39:00Z

I also switched to using the full time zone name (per Basil's advice), since it is less ambiguous.

我还改用了完整的时区名称(根据 Basil 的建议),因为它不那么模糊。

回答by coladict

Forget the old TimeZone class. Use ZoneId, because it's properly thread-safe and you can just use a final static field to store the zone.

忘记旧的 TimeZone 类。使用ZoneId,因为它是线程安全的,您可以只使用最终静态字段来存储区域。

LocalDateTime dateTime = LocalDateTime.of(2017, Month.JUNE, 1, 13, 39);
ZonedDateTime.of(dateTime, ZoneId.of("ECT")).toInstant();

回答by Florian

I think the following code should work:

我认为以下代码应该有效:

LocalDateTime time = LocalDateTime.of(2017, Month.JUNE, 15, 13, 39);
ZonedDateTime.of(time, TimeZone.getTimeZone("ZONE").toZoneId()).toInstant();

You just have to replace "ZONE" with the timezone you need.

您只需将“ZONE”替换为您需要的时区。