Java - How to change ZonedDateTime to TimeStamp

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

ZonedDateTime is a Time API added in JAVA8.

Unlike LocalDateTime, ZonedDateTime has zone information, so you can see how much time difference is in UTC.

ZonedDateTime => Timestamp

How to convert from ZonedDateTime to Timestamp.

package time;

import java.sql.Timestamp;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Example03 {
    public static void main(String args[]) {
        ZonedDateTime utcDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
        System.out.println(utcDateTime);

        // ZonedDateTime => Timestamp 변
        Timestamp timestamp = Timestamp.valueOf(utcDateTime.toLocalDateTime());
        System.out.println(timestamp);

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

        // Convert ZonedDateTime to Instant object => Convert Timestamp
        Timestamp timestamp2 = Timestamp.from(utcDateTime.toInstant());
        System.out.println(timestamp2);
    }
}

result

2019-10-31T00:09:01.962Z[UTC]
2019-10-31 00:09:01.962
1572448141962
2019-10-31 09:09:01.962

Timestamp => ZonedDateTime

How to convert from Timestamp to ZonedDateTime.

package time;

import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

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

        Timestamp timestamp = Timestamp.from(Instant.now());
        System.out.println(timestamp);

        // Timestamp => LocalDateTime 변
        LocalDateTime noTimeZoneLocalDateTime = timestamp.toLocalDateTime();

        // LocalDateTime => ZonedDateTime (Zone = Seoul)
        ZonedDateTime zonedDateTime =
            noTimeZoneLocalDateTime.atZone(ZoneId.of("Asia/Seoul"));
        System.out.println(zonedDateTime);

        // LocalDateTime => ZonedDateTime (Zone = UTC)
        ZonedDateTime zonedDateTime1 =
            noTimeZoneLocalDateTime.atZone(ZoneId.of("UTC"));
        System.out.println(zonedDateTime1);

        // LocalDateTime => ZonedDateTime (Zone = "-06:00")
        ZonedDateTime zonedDateTime2 =
            noTimeZoneLocalDateTime.atZone(ZoneId.of("-06:00"));
        System.out.println(zonedDateTime2);
    }
}

result

2019-10-31 09:10:35.032
2019-10-31T09:10:35.032+09:00[Asia/Seoul]
2019-10-31T09:10:35.032Z[UTC]
2019-10-31T09:10:35.032-06:00

Reference

codechachaCopyright ©2019 codechacha