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 t…


This content originally appeared on DEV Community and was authored by taijidude

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


This content originally appeared on DEV Community and was authored by taijidude


Print Share Comment Cite Upload Translate Updates
APA

taijidude | Sciencx (2024-09-18T13:43:26+00:00) Convert LocalDateTime to Date and back. Retrieved from https://www.scien.cx/2024/09/18/convert-localdatetime-to-date-and-back/

MLA
" » Convert LocalDateTime to Date and back." taijidude | Sciencx - Wednesday September 18, 2024, https://www.scien.cx/2024/09/18/convert-localdatetime-to-date-and-back/
HARVARD
taijidude | Sciencx Wednesday September 18, 2024 » Convert LocalDateTime to Date and back., viewed ,<https://www.scien.cx/2024/09/18/convert-localdatetime-to-date-and-back/>
VANCOUVER
taijidude | Sciencx - » Convert LocalDateTime to Date and back. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/18/convert-localdatetime-to-date-and-back/
CHICAGO
" » Convert LocalDateTime to Date and back." taijidude | Sciencx - Accessed . https://www.scien.cx/2024/09/18/convert-localdatetime-to-date-and-back/
IEEE
" » Convert LocalDateTime to Date and back." taijidude | Sciencx [Online]. Available: https://www.scien.cx/2024/09/18/convert-localdatetime-to-date-and-back/. [Accessed: ]
rf:citation
» Convert LocalDateTime to Date and back | taijidude | Sciencx | https://www.scien.cx/2024/09/18/convert-localdatetime-to-date-and-back/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.