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
Convert between LocalDate and sql.Date
提问by maja
What's the correct way to convert between java.sql.Date
and LocalDate
(Java8)?
在java.sql.Date
和LocalDate
(Java8)之间转换的正确方法是什么?
采纳答案by maja
The Java 8 version (and later) of java.sql.Date
has built in support for LocalDate
, including toLocalDate
and valueOf(LocalDate)
.
的 Java 8 版本(及更高版本)java.sql.Date
内置了对 的支持LocalDate
,包括toLocalDate
和valueOf(LocalDate)
。
To convert from LocalDate
to java.sql.Date
you can use
要从转换LocalDate
为java.sql.Date
您可以使用
java.sql.Date.valueOf( localDate );
And to convert from java.sql.Date
to LocalDate
:
并转换java.sql.Date
为LocalDate
:
sqlDate.toLocalDate();
Time zones:
时区:
The LocalDate
type stores no time zone information, while java.sql.Date
does. 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();