Mutual conversion of Date and LocalDateTime in Java8

Keywords: PHP Java

I. converting Date to LocalDateTime in Java 8

Method 1:

To convert Date to LocalDatetime, we can use the following methods:

1. Get zonedatetime from date and use its method toLocalDateTime() to get LocalDateTime
 2. Use the Instant() factory method of LocalDateTime

Example:

package insping;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class Test {

    public static void main(String[] args) {
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();

        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        System.out.println("Date = " + date);
        System.out.println("LocalDateTime = " + localDateTime);

    }
}

Result:

Date = Fri Jun 16 15:35:26 CST 2017
LocalDateTime = 2017-06-16T15:35:26.970

Method 2:

We can also use the FactoryInput() method of LocalDateTime to use the default time zone of the system.

LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), zoneId);

2. Convert LocalDateTime to Date in Java 8

To convert LocalDateTime back to java.util.Date, we can use the following steps:

1. Use atZone() method to convert LocalDateTime to zonedatetime 
2. Convert ZonedDateTime to Instant and get Date from it

Example:

package insping;

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

public class Test {

    public static void main(String[] args) {
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.now();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);

        Date date = Date.from(zdt.toInstant());

        System.out.println("LocalDateTime = " + localDateTime);
        System.out.println("Date = " + date);
    }
}

Result:

LocalDateTime = 2017-06-16T15:38:48.580
Date = Fri Jun 16 15:38:48 CST 2017
Original address: https://blog.csdn.net/hspingcc/article/details/73332380

Posted by dm404 on Thu, 31 Oct 2019 18:08:00 -0700