首页 >Java >java教程 >Convert LocalDateTime to Date

Convert LocalDateTime to Date

DDD
DDD原创
2024-09-19 02:13:02652浏览

Convert LocalDateTime to Date

At the moment i have to write a lot of Integeration Tests for a migration project. The old code uses java.util.Date a lot, but the project uses Java 17. So i wanted to use the newer Date Classes for my tests.

I used the following two helper methods to convert Date to LocalDateTime and back.

private LocalDateTime toLocalDateTime(Date toConvert) {
        var instant = toConvert.toInstant();
        var zonedDateTime = instant.atZone(ZoneId.systemDefault());
        return zonedDateTime.toLocalDateTime();
    }

    private Date toDate(LocalDateTime toConvert) {
        var zonedDateTime = toConvert.atZone(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }

以上是Convert LocalDateTime to Date的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn