Java 8 – Convert LocalDate and LocalDateTime to Date

A Java example to convert Java 8 java.time.LocalDate and java.time.LocalDateTime back to the classic java.uti.Date.

JavaDateExample.java

package com.mkyong.time;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

public class JavaDateExample {

    public static void main(String[] args) {

        // LocalDate -> Date
        LocalDate localDate = LocalDate.of(2020, 2, 20);
        Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

        // LocalDateTime -> Date
        LocalDateTime localDateTime = LocalDateTime.of(2020,2,20,21,46,31);
        Date date2 = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

        // ZonedDateTime -> Date
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
        Date date3 = Date.from(zonedDateTime.toInstant());

    }

}

Output


Thu Feb 20 00:00:00 MYT 2020
Thu Feb 20 21:46:31 MYT 2020
Thu Feb 20 21:46:31 MYT 2020

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar