LocalDate 到 java.util.Date 反之亦然最简单的转换? [英] LocalDate to java.util.Date and vice versa simplest conversion?

查看:21
本文介绍了LocalDate 到 java.util.Date 反之亦然最简单的转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以将 LocalDate(在 Java 8 中引入)转换为 java.util.Date 对象?

简单"是指比这更简单:

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

这对我来说似乎有点尴尬.

既然我们只对日期部分感兴趣,两个对象中都没有时区信息,为什么要明确引入时区呢?转换时应隐式采用午夜时间和系统默认时区.

解决方案

tl;dr

<块引用>

是否有一种简单的方法可以将 LocalDate(在 Java 8 中引入)转换为 java.util.Date 对象?简单"是指比这更简单

没有.你做得对,而且尽可能简洁.

java.util.Date.from(//从现代 java.time 类转换为麻烦的旧遗留类.除非必须,否则不要这样做,以便与尚未为 java.time 更新的旧代码进行交互.myLocalDate//`LocalDate` 类表示仅日期,没有时间,没有时区,也没有从 UTC 偏移..atStartOfDay(//让 java.time 确定该区域中那个日期的一天中的第一个时刻.永远不要假设一天从 00:00:00 开始.ZoneId.of( "America/Montreal")//使用适当的名称以`Continent/region` 格式指定时区,不要使用3-4 个字母的伪区域,例如PST"、CST"、IST".)//生成一个 `ZonedDateTime` 对象..toInstant()//提取一个 `Instant` 对象,时刻始终采用 UTC.)

阅读下面的问题,然后思考.怎么可能更简单?如果你问我约会从几点开始,除了问你在哪里?"之外,我还能怎么回答?新的一天在法国巴黎比在加州蒙特利尔更早开始,在加尔各答更早,在新西兰奥克兰甚至更早,所有不同的时刻.

因此,在将仅日期 (LocalDate) 转换为日期时间时,我们必须应用时区 (ZoneId) 以获得一个分区值 (ZonedDateTime),然后移动到 UTC (Instant) 以匹配 java.util.Date 的定义.>

详情

首先,尽可能避免使用旧的遗留日期时间类,例如 java.util.Date.它们设计不佳,令人困惑且麻烦.它们被 java.time 类取代是有原因的,实际上,出于很多原因.

但如果必须,您可以将 java.time 类型转换为/从 java.time 类型转换为旧类型.寻找添加到旧类中的新转换方法.

java.util.Datejava.time.LocalDate

请记住,java.util.Date 用词不当,因为它表示日期 加上 UTC 时间.相比之下,

ThreeTen-Extra 项目扩展了 java.time额外的课程.该项目是未来可能添加到 java.time 的试验场.您可能会在这里找到一些有用的类,例如 Interval, YearWeek, YearQuarter更多.

Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object?

By 'simple', I mean simpler than this:

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

which seems a bit awkward to me.

Since we are interested only in the date portion and there is no timezone information in neither of the objects, why introduce time zones explicitly? The midnight time and the system default timezone should be taken implicitly for the conversion.

解决方案

tl;dr

Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object? By 'simple', I mean simpler than this

Nope. You did it properly, and as concisely as possible.

java.util.Date.from(                     // Convert from modern java.time class to troublesome old legacy class.  DO NOT DO THIS unless you must, to inter operate with old code not yet updated for java.time.
    myLocalDate                          // `LocalDate` class represents a date-only, without time-of-day and without time zone nor offset-from-UTC. 
    .atStartOfDay(                       // Let java.time determine the first moment of the day on that date in that zone. Never assume the day starts at 00:00:00.
        ZoneId.of( "America/Montreal" )  // Specify time zone using proper name in `continent/region` format, never 3-4 letter pseudo-zones such as "PST", "CST", "IST". 
    )                                    // Produce a `ZonedDateTime` object. 
    .toInstant()                         // Extract an `Instant` object, a moment always in UTC.
)

Read below for issues, and then think about it. How could it be simpler? If you ask me what time does a date start, how else could I respond but ask you "Where?"?. A new day dawns earlier in Paris FR than in Montréal CA, and still earlier in Kolkata IN, and even earlier in Auckland NZ, all different moments.

So in converting a date-only (LocalDate) to a date-time we must apply a time zone (ZoneId) to get a zoned value (ZonedDateTime), and then move into UTC (Instant) to match the definition of a java.util.Date.

Details

Firstly, avoid the old legacy date-time classes such as java.util.Date whenever possible. They are poorly designed, confusing, and troublesome. They were supplanted by the java.time classes for a reason, actually, for many reasons.

But if you must, you can convert to/from java.time types to the old. Look for new conversion methods added to the old classes.

java.util.Datejava.time.LocalDate

Keep in mind that a java.util.Date is a misnomer as it represents a date plus a time-of-day, in UTC. In contrast, the LocalDate class represents a date-only value without time-of-day and without time zone.

Going from java.util.Date to java.time means converting to the equivalent class of java.time.Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant();

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still "yesterday" in Montréal Québec.

So we need to move that Instant into a time zone. We apply ZoneId to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

From there, ask for a date-only, a LocalDate.

LocalDate ld = zdt.toLocalDate();

java.time.LocalDatejava.util.Date

To move the other direction, from a java.time.LocalDate to a java.util.Date means we are going from a date-only to a date-time. So we must specify a time-of-day. You probably want to go for the first moment of the day. Do not assume that is 00:00:00. Anomalies such as Daylight Saving Time (DST) means the first moment may be another time such as 01:00:00. Let java.time determine that value by calling atStartOfDay on the LocalDate.

ZonedDateTime zdt = myLocalDate.atStartOfDay( z );

Now extract an Instant.

Instant instant = zdt.toInstant();

Convert that Instant to java.util.Date by calling from( Instant ).

java.util.Date d = java.util.Date.from( instant );

More info


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

这篇关于LocalDate 到 java.util.Date 反之亦然最简单的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆