I have UTC time offsets for specific operations stored like this: (this one is for UTC+2)
double utc = 2.0;
How can I get current time for that timezone using this double time offset in Java?
You may combine
ZoneOffset.ofTotalSeconds to get the offset zone from the hour offsetInstant.atOffset to get the OffsetDatetime from current Instant and the ZoneOffsetOffsetDateTime odt = Instant.now().atOffset(ZoneOffset.ofTotalSeconds((int) (2.0*3600)));
Code DemoFirst you need to convert the double value to a ZoneOffset:
double utc = 2.0;
ZoneOffset offset = ZoneOffset.ofTotalSeconds((int) (utc * 3600));
You can then get the current time:
OffsetDateTime now = Instant.now().atOffset(offset);
Sample Output
2020-09-22T21:16:42.816236600+02:00
Two other alternatives:
Using:
double utc = 2.0;
Alternative 1:
ZonedDateTime nowAlt1 = Instant.now().atZone(ZoneOffset.ofTotalSeconds((int) utc * 3600));
Alternative 2:
ZonedDateTime nowAlt2 = ZonedDateTime.ofInstant(Instant.now(), ZoneOffset.ofTotalSeconds((int) utc * 3600));
Alternative 1 and 2 in context:
public static void main(String[] args) {
double utc = 2.0;
ZonedDateTime nowAlt1 = Instant.now().atZone(ZoneOffset.ofTotalSeconds((int) utc * 3600));
ZonedDateTime nowAlt2 = ZonedDateTime.ofInstant(Instant.now(), ZoneOffset.ofTotalSeconds((int) utc * 3600));
System.out.println("nowAlt1: " + nowAlt1);
System.out.println("nowAlt2: " + nowAlt2);
}
Output:
nowAlt1: 2020-09-22T23:15:00.254912800+02:00
nowAlt2: 2020-09-22T23:15:00.253915600+02:00
Read more about java.time here, will give you an idea when to use the different types of java.time: What's the difference between Instant and LocalDateTime?