Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.sql.Timestamp: changing timezone of Timestamp

Tags:

java

How can I change timezone of a java.sql.Timestamp object which was initially, instantiated to CST, to GMT?

like image 632
abson Avatar asked Dec 20 '11 07:12

abson


2 Answers

java.sql.Timestamp objects don't have time zones - they are instants in time, like java.util.Date.

If you're thinking of them as being in a particular time zone, you may either be getting confused due to misleading output (e.g. something automatically converting that instant into a local time using a default time zone) or you may have created the data in an inappropriate way. The answer you need will depend on the details of your situation.

For example, if you just want to display a Timestamp value in a particular time zone, you can use SimpleDateFormat, set the time zone appropriately, and just format the Timestamp (as it extends Date). I don't believe that will allow you to display as much precision as the timestamp stores internally, but that may not be a problem for you.

If your data has been created incorrectly then there may or may not be a way to "correct" it - there may be some ambiguities due to daylight saving time changes, for example. However, the more we know about it the better we'll be able to help you.

like image 197
Jon Skeet Avatar answered Sep 19 '22 17:09

Jon Skeet


Some Timestamp constructors do depend on the default timezone. One way to avoid this is to use the constructor that takes a long:

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
like image 45
Mikael Valot Avatar answered Sep 17 '22 17:09

Mikael Valot