"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Convert LocalDateTime to Date and back

Convert LocalDateTime to Date and back

Published on 2024-11-08
Browse:200

Convert LocalDateTime to Date and back

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());
}
Release Statement This article is reproduced at: https://dev.to/taijidude/convert-localdatetime-to-date-and-back-4lkj?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3