Java 8添加了一个新的java.time API来处理日期和时间(JSR 310).
我有日期和时间作为字符串(例如"2014-04-08 12:30").如何LocalDateTime从给定的字符串中获取实例?
在我完成LocalDateTime对象的使用之后:如何将LocalDateTime实例转换回具有与上面所示格式相同的字符串?
我有一个epoch秒和一个zoneId,方法1.它可以转换为LocalDateTime与系统默认的zoneId,但我找不到方法将第二个转换为LocalDateTime by method2,因为没有ZoneOffset.systemDefault.我认为它是模糊的.
import java.time.{Instant, LocalDateTime, ZoneId, ZoneOffset}
val epochSecond = System.currentTimeMillis() / 1000
LocalDateTime.ofInstant(Instant.ofEpochSecond(epochSecond), ZoneId.systemDefault())//method1
LocalDateTime.ofEpochSecond(epochSecond, 0, ZoneOffset.MAX)//method2
Run Code Online (Sandbox Code Playgroud) 使用Java 1.8.0_51以下代码(取自Unable从TemporalAccessor获取OffsetDateTime)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneId.of("Europe/Berlin"));
OffsetDateTime offsetDateTime = ZonedDateTime.parse("20151113", formatter).toOffsetDateTime();
System.out.println(offsetDateTime.format(DateTimeFormatter.ISO_DATE));
Run Code Online (Sandbox Code Playgroud)
抛出异常:
java.time.format.DateTimeParseException: Text '20151113' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO,Europe/Berlin resolved to 2015-11-13 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)
Run Code Online (Sandbox Code Playgroud)
这次我做错了什么?
假设我有一个 ZonedDateTime 2018-10-30T18:04:58.874Z:如何将其转换为 OffsetDateTime2018-10-30T13:04:58.874-05:00
我更喜欢偏移量是默认/系统偏移量,例如从OffsetDateTime.now().