Home >Java >javaTutorial >Convert LocalDateTime to Date

Convert LocalDateTime to Date

DDD
DDDOriginal
2024-09-19 02:13:02651browse

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());
    }

The above is the detailed content of Convert LocalDateTime to Date. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn