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

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

问题描述

有没有一种简单的方法来将 LocalDate (引入Java 8)转换为 java.util.Date 对象?

通过'simple',我的意思比这更简单:

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.

推荐答案

其实有。有一个静态方法 valueOf java.sql.Date 对象中。所以我们有

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.

从文档:


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

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

java.sql.Date 子类 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天全站免登陆