Java.sql.Timestamp: change timezone timestamp

How to change the time zone of a java.sql.Timestamp object that was originally created in CST in GMT?

+4
source share
2 answers

java.sql.Timestamp objects do not have time zones - they are points in time, for example java.util.Date .

If you think that they are in a specific time zone, you may be confused due to misleading output (for example, something will automatically convert this moment to local time using the default time zone), or you may created data inappropriately. The answer you need will depend on the details of your situation.

For example, if you just want to display the Timestamp value in a specific time zone, you can use SimpleDateFormat , set the time zone accordingly and simply format the Timestamp (as it extends Date ). I do not believe that this will allow you to display the same accuracy as the temporary memory stored inside, but this may not be a problem for you.

If your data was not created correctly, then there may or may not be a way to β€œfix” it - for example, some uncertainties may arise due to changes in daylight saving time. However, the more we know about it, the better we can help you.

+11
source

Some Timestamp constructors depend on the default time zone. One way to avoid this is to use a constructor that takes a lot of time:

 TimeZone.setDefault(TimeZone.getTimeZone("GMT")) Timestamp.valueOf("2016-10-26 23:00:00").getTime() res16: Long = 1477522800000 // This is what we want TimeZone.setDefault(TimeZone.getTimeZone("GMT-1")) Timestamp.valueOf("2016-10-26 23:00:00").getTime() res14: Long = 1477526400000 new Timestamp(OffsetDateTime.of(2016,10,26,23,0,0,0,ZoneOffset.UTC).toInstant.toEpochMilli).getTime res15: Long = 1477522800000 // We get the same result at in GMT 
+1
source

Source: https://habr.com/ru/post/1387156/


All Articles