将 LocalDate 转换为 java.util.Date 时缺少时间信息
我的输入日期格式为"2019-08-30T19:47:22+00:00"(字符串(。我必须将其转换为java.util.Data。我想用java 8来做。
String input = "2019-08-30T19:47:22+00:00";
Date date = null;
LocalDate dateTime = LocalDate.parse(input, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
date = Date.from(dateTime.atStartOfDay(ZoneId.systemDefault()).toInstant());
System.out.println("Parsed from LoacalDate: " + date);
System.out.println("From new Date(): " + new Date());
输出
- 解析自 Loacal日期: 2019 年 8 月 30 日星期五 00:00:00CDT 来自新
- 日期((: 2019年8月30日星期五 17:16:23 CDT
在输出时间信息丢失。如何获取时间信息?
tl;博士
LocalDate
只存储一个日期,所以使用错误的类。
java.util.Date // Terrible class, now legacy. Avoid. Replaced by `java.time.Instant` in JSR 310. Use only where required, to interoperate with old code not yet updated for java.time.
.from( // Convert from modern `Instant` to legacy `Date`.
OffsetDateTime // The modern class to represent a moment in the context of an offset-from-UTC (a number of hours-minutes-seconds). Not to be confused with a time zone, which is a history of changes to the offset used by the people of a particular region.
.parse( "2019-08-30T19:47:22+00:00" ) // Parse text into an `OffsetDateTime` object.
.toInstant() // Extract an `Instant`, a more basic building-block class that represent a moment in UTC (an offset of zero).
)
.toString() // Generates text representing the value of the `Date`. But this method lies! It dynamically applies your JVM’s current default time zone while generating the text.
请注意,java.util.Date::toString
说谎!该方法动态应用 JVM 的当前默认时区,同时生成文本以表示实际采用 UTC 的值。从不使用此Date
类的众多原因之一。
详
您使用了错误的类。
LocalDate
LocalDate
仅表示日期,不表示一天中的时间,不表示时区或偏移量。
通过将表示时刻的输入解析为简单的日期,您可以减少一天中的时间和 UTC 的偏移量。
OffsetDateTime
您的输入"2019-08-30T19:47:22+00:00"
表示一个时刻:日期、一天中的时间、与 UTC 的偏移量为零小时-分钟-秒。因此,将其解析为OffsetDateTime
.
OffsetDateTime odt = OffsetDateTime.parse( "2019-08-30T19:47:22+00:00" ) ;
避免使用传统的日期时间课程
java.util.Date
类很糟糕,不应该再使用。几年前,随着JSR 310的采用,它被现代java.time类所取代。
但是,如果必须与尚未更新到java.time的旧代码进行互操作,则可以来回转换。查看添加到旧类的新to…
/from…
方法。
相当于java.util.Date
是java.time.Instant
,两者都代表UTC的一个时刻(尽管分辨率不同,毫秒和纳秒(。因此,从我们更灵活的OffsetDateTime
中提取一个基本的Instant
对象。
Instant instant = odt.toInstant() ;
java.util.Date d = Date.from( instant ) ;
我能够使用以下代码片段使其工作
LocalDateTime dateTime = LocalDateTime.parse(input,DateTimeFormatter.ISO_OFFSET_DATE_TIME);
date = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("Parsed from LoacalDate:" + date);
System.out.println("From new Date():" + new Date());