Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make java.sql.Timestamp UTC time? [duplicate]

public static void main(String[] args) {

    LocalDateTime ldt = LocalDateTime.now();

    ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());

    Instant instant = Instant.from(zdt);

    Timestamp timestamp = Timestamp.from(instant);

    System.out.println(ldt + "\n");

    System.out.println(zdt + "\n");

    System.out.println(instant + "\n");

    System.out.println(timestamp + "\n");
}

And it prints:

2017-05-07T18:13:26.969

2017-05-07T18:13:26.969-04:00[America/New_York]

2017-05-07T22:13:26.969Z

2017-05-07 18:13:26.969

How can I make an SQL Timestamp save with the same time as the Instant? I need to be able to get the Timestamp from anywhere and convert it to whatever time it happens to be in that part of the world. The problem is that it keeps saving as the same time as whatever my system clock happens to be set at.

like image 601
Skywarp Avatar asked May 07 '17 22:05

Skywarp


People also ask

Is Java sql timestamp UTC?

Instant and java. sql. Timestamp classes represent a point on the timeline in UTC. In other words, they represent the number of nanoseconds since the Java epoch.

What is the timezone of Java sql timestamp?

GMT timezone is sort of standard timezone for recording date and timestamp. if your application is not using any local timezone that you can use GMT for storing values on server.

Is timestamp stored in UTC?

For timestamp with time zone , the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT ). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone.


1 Answers

You are best to get a Timestamp from a LocalDateTime, rather than from an Instant.

The first step is to take your ZonedDateTime and convert it to GMT:

ZonedDateTime gmt = zdt.withZoneSameInstant(ZoneId.of("GMT"));

Then you can convert it to a Timestamp via a LocalDateTime:

Timestamp timestamp = Timestamp.valueOf(gmt.toLocalDateTime());
like image 165
Joe C Avatar answered Sep 19 '22 13:09

Joe C