Convert LocalDateTime to Date and back
taijidude

taijidude @taijidude

About: Java Developer. Love to read and learn. Hobbies: - tabletop rpgs - boardgames - videogames - cooking - kettlebell

Location:
Hannover, Germany
Joined:
Jul 22, 2020

Convert LocalDateTime to Date and back

Publish Date: Sep 18 '24
0 0

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 runs in 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());
}
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

Не удалось загрузить комментарии.
Add comment