Java 在 LocalDate 和 sql.Date 之间转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29750861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:33:09  来源:igfitidea点击:

Convert between LocalDate and sql.Date

javadatejava-8converterjava-time

提问by maja

What's the correct way to convert between java.sql.Dateand LocalDate(Java8)?

java.sql.DateLocalDate(Java8)之间转换的正确方法是什么?

采纳答案by maja

The Java 8 version (and later) of java.sql.Datehas built in support for LocalDate, including toLocalDateand valueOf(LocalDate).

的 Java 8 版本(及更高版本)java.sql.Date内置了对 的支持LocalDate,包括toLocalDatevalueOf(LocalDate)

To convert from LocalDateto java.sql.Dateyou can use

要从转换LocalDatejava.sql.Date您可以使用

java.sql.Date.valueOf( localDate );

And to convert from java.sql.Dateto LocalDate:

并转换java.sql.DateLocalDate

sqlDate.toLocalDate();

Time zones:

时区:

The LocalDatetype stores no time zone information, while java.sql.Datedoes. Therefore, when using the above conversions, the results depend on the system's default timezone (as pointed out in the comments).

LocalDate类型不存储时区信息,而存储java.sql.Date。因此,在使用上述转换时,结果取决于系统的默认时区(如评论中指出的)。

If you don't want to rely on the default timezone, you can use the following conversion:

如果不想依赖默认时区,可以使用以下转换:

Date now = new Date();
LocalDate current = now.toInstant()
                       .atZone(ZoneId.systemDefault()) // Specify the correct timezone
                       .toLocalDate();