Convert Date to LocalDate and LocalDateTime Java 8

This Convert Date to LocalDate and LocalDateTime Java 8 tutorial shows you my knowledge about conversion ways between the classic java.util.Date, LocalDate, and LocalDateTime. I shows aslo you how to convert LocalDate and LocalDateTime to java.util.Date.

As you know the class java.util.Date represents a specific instant in time, with millisecond precision. It means that java.util.Date doesn’t contain time zone and only represents the number of seconds passed since the Unix epoch time – 1970-01-01T00:00:00Z (midnight at the start of January 1, 1970 GMT/UTC).

Let’s begin:

Convert Date to LocalDate and LocalDateTime Java 8

Date to java.time.LocalDate

Date to java.time.LocalDateTime

Date to java.time.ZonedDateTime

Create a program for testing
We create a main class show what the above examples print out

Run above main class as Java application and the output is printed out like below

Convert Date to LocalDate and LocalDateTime Java 8

Let’s look into the above output, you will see the date with time zone. This is not what we have just told the above. If you have a look on the method toString() of the Date class, you will see the system default time zone will be appended on Date object. So that Date object and time zone always are printed together.

Noticed that the new Java 8 java.time.Instant is equivalent with the classic java.util.Date

Convert LocalDate, LocalDateTime and ZonedDateTime to Date

Now, we create a main class to demonstrate how to Convert LocalDate, LocalDateTime and ZonedDateTime to java.util.Date.

Run above main as Java application and produce the output like below

Convert LocalDate, LocalDateTime and ZonedDateTime to Date

That’s all on the Convert Date to LocalDate and LocalDateTime Java 8.

References
JSR 310: Date and Time API


Unix time
Instant JavaDoc

Leave a Comment

*

Please share it if you found this useful
Hide Buttons