简体   繁体   中英

java.sql.Timestamp: changing timezone of Timestamp

如何将最初实例化为CST的java.sql.Timestamp对象的时区更改为GMT?

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 (eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM