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

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

问题描述

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

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.

推荐答案

实际上有。有一个静态方法 java.sql.Date 对象中的> valueOf 就是这样做的。所以我们有

Actually there is. There is a static method valueOf in the java.sql.Date object which does exactly that. So we have

java.util.Date date = java.sql.Date.valueOf(localDate);

就是这样。没有明确设置时区,因为本地时区是隐式的。

and that's it. No explicit setting of time zones because the local time zone is taken implicitly.

来自docs:


提供的LocalDate被解释为本地
时区的本地日期。

The provided LocalDate is interpreted as the local date in the local time zone.

java.sql.Date subslasses java.util.Date 所以结果是 java.util。日期也。

The java.sql.Date subclasses java.util.Date so the result is a java.util.Date also.

对于反向操作,有一个 toLocalDate 方法。所以我们有:

And for the reverse operation there is a toLocalDate method in the java.sql.Date class. So we have:

LocalDate ld = new java.sql.Date(date.getTime())。toLocalDate();

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

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