Java 8 – Convert LocalDateTime to Timestamp

In Java, we can use Timestamp.valueOf(LocalDateTime) to convert a LocalDateTime into a Timestamp.

1. LocalDateTime <-> Timestamp

Java example to convert java.time.LocalDateTime to java.sql.Timestamp and vice verse.

TimeExample.java

package com.mkyong;

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

public class TimeExample {

    public static void main(String[] args) {

        //  LocalDateTime to Timestamp
        LocalDateTime now = LocalDateTime.now();
        Timestamp timestamp = Timestamp.valueOf(now);

        System.out.println(now);            // 2019-06-14T15:50:36.068076300
        System.out.println(timestamp);      // 2019-06-14 15:50:36.0680763

        //  Timestamp to LocalDateTime
        LocalDateTime localDateTime = timestamp.toLocalDateTime();

        System.out.println(localDateTime);  // 2019-06-14T15:50:36.068076300

    }
}

2. LocalDate <-> Timestamp

As title.

TimeExample2.java

package com.mkyong.jdbc;

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

public class TimeExample2 {

    public static void main(String[] args) {

        //  LocalDate to Timestamp
        LocalDate now = LocalDate.now();
        Timestamp timestamp = Timestamp.valueOf(now.atStartOfDay());

        System.out.println(now);        // 2019-06-14
        System.out.println(timestamp);  // 2019-06-14 00:00:00.0

        //  Timestamp to LocalDate
        LocalDate localDate = timestamp.toLocalDateTime().toLocalDate();
        System.out.println(localDate);  // 2019-06-14

    }
}

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