Java - How to change LocalDateTime to TimeStamp

How to change java.time.LocalDate, java.time.LocalDateTime to java.sql.Timestamp. Or vice versa, here`s how to change it.

LocalDateTime, LocalDate are Time APIs added in JAVA8.

LocalDateTime <=> Timestamp

How to convert LocalDateTime to Timestamp and Timestamp to LocalDateTime.

package time;

import java.sql.Timestamp;
import java.time.LocalDateTime;

public class Example01 {
    public static void main(String args[]) {

        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);

        // LocalDateTime -> Convert to Timestamp
        Timestamp timestamp2 = Timestamp.valueOf(localDateTime);
        System.out.println(timestamp2);

        // Time output in milliseconds from 1970/01/01 00:00:00 GMT
        System.out.println(timestamp2.getTime());

        // Timestamp -> Convert to LocalDateTime
        LocalDateTime localDateTime1 = timestamp2.toLocalDateTime();
        System.out.println(localDateTime1);
    }
}

result

2019-10-31T08:45:54.874
2019-10-31 08:45:54.874
1572479154874
2019-10-31T08:45:54.874

LocalDate <=> Timestamp

How to convert LocalDate to Timestamp and Timestamp to LocalDate.

package time;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;

public class Example02 {
    public static void main(String args[]) {

        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);

        // Convert to LocalDate -> Timestamp
        Timestamp timestamp = Timestamp.valueOf(localDate.atStartOfDay());
        System.out.println(timestamp);
        System.out.println(timestamp.getTime());

        // Timestamp -> Convert to LocalDate
        LocalDate localDate1 = timestamp.toLocalDateTime().toLocalDate();
        System.out.println(localDate1);
    }
}

result

2019-10-31
2019-10-31 00:00:00.0
1572447600000
2019-10-31

Reference

codechachaCopyright ©2019 codechacha