-1

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?

Marcus
  • 131
  • 9

3 Answers3

5

You may combine

OffsetDateTime odt = Instant.now().atOffset(ZoneOffset.ofTotalSeconds((int) (2.0*3600)));

Code Demo

azro
  • 53,056
  • 7
  • 34
  • 70
  • Better to use `Instant.now().atOffset(...)`. Less waste. Clearer intent. – Andreas Sep 22 '20 at 19:18
  • While the answer is useful enough not to be down-voted, it doesn't actually answer the question, which was *"How can I get current time for that timezone **using this `double`** time offset in Java?"* – Andreas Sep 22 '20 at 19:19
  • @Andreas the cast from double to int ? Because `ZoneOffset.ofHours(2)` seems nicer than `ZoneOffset.ofTotalSeconds(3600 * 2)` – azro Sep 22 '20 at 19:22
  • `double india = 5.5;` Ehhh.... No, cast to `int` will not do. Or how about `double offset = 1.3255555555555556;`, aka `1:19:32`, used by `Europe/Amsterdam` 1916-1937? – Andreas Sep 22 '20 at 19:30
2

First 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
Andreas
  • 154,647
  • 11
  • 152
  • 247
1

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?

DigitShifter
  • 801
  • 5
  • 12