Convert between LocalDate and sql.Date [duplicate]

こ雲淡風輕ζ 提交于 2019-11-26 20:04:54

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

To convert from LocalDate to java.sql.Date you can use

java.sql.Date.valueOf( localDate );

And to convert from java.sql.Date to 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).

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!