Reputation: 25
Consider Timestamp sourceTimestamp
belonging to Timezone sourceTimezone
. I want to convert sourceTimestamp
to a new Timestamp
belonging to Timezone newTimezone
.
How do I get this new Timestamp
?
Basically I want a function like
Timestamp myFunction(Timestamp sourceTimestamp , Timezone sourceTimezone , Timezone newTimezone){
...
...
return newTimestamp
}
Timestamp
belongs to package java.sql.Timestamp
and Timezone
belongs to import java.util.TimeZone
.
Upvotes: 0
Views: 44
Reputation: 18568
If Java 8 is available to you, you will be best advised to use java.time
.
Fortunately, a java.sql.Timestamp
has methods to convert its values from and to objects/classes from java.time
You could write a method that takes a Timestamp
and two ZoneId
s:
public static Timestamp convertZone(Timestamp time, ZoneId originZone, ZoneId targetZone) {
// create a zone-aware datetime object to fully represent the input
ZonedDateTime originZdt = time.toLocalDateTime().atZone(originZone);
/*
* then change its zone, keeping the epoch millis
* (only time of day changes according to the zone)
*/
ZonedDateTime targetZdt = originZdt.withZoneSameInstant(targetZone);
// and return a Timestamp of the date and time of the adjusted
return Timestamp.valueOf(targetZdt.toLocalDateTime());
}
and then use it somehow like this:
public static void main(String[] args) throws Exception {
// create some example Timestamp
Timestamp sourceTimestamp = Timestamp.from(Instant.now());
// define the zones
ZoneId sourceTimezone = ZoneId.of("Europe/Amsterdam");
ZoneId newTimezone = ZoneId.of("Asia/Kolkata");
// use the method to convert the values
Timestamp adjusted = convertZone(sourceTimestamp, sourceTimezone, newTimezone);
// print them
System.out.println("source: " + sourceTimestamp);
System.out.println("target: " + adjusted);
}
Some moments (Instant
s ;-) ) ago, the output on my machine was:
source: 2021-08-04 08:50:22.913429
target: 2021-08-04 12:20:22.913429
Upvotes: 1