Java 8 Convert LocalDateTime to Timestamp
By:Roy.LiuLast updated:2019-08-11
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
From:一号门
Next:Java Events 2019
COMMENTS