Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed Clock and LocalDateTime

Tags:

java

java-time

For testing purposes I want to create a fixed Clock with a time zone:

Clock c= Clock.fixed(Instant.parse("2018-04-29T10:15:30.00Z"), ZoneId.of("Europe/Berlin"));
//yields FixedClock[2018-04-29T10:15:30Z,Europe/Berlin]

Now I want to use the Clock wit LocalDateTime:

LocalDateTime.now(c);
//yields 2018-04-29T12:15:30

Why I'm getting this offset by two hours? Is there a UTC conversion somewhere? What would I have to do to generate a fixed Clock with time zone and LocalDate.now(c) yields the same time?

like image 286
user15110545 Avatar asked Oct 23 '25 16:10

user15110545


1 Answers

2018-04-29T10:15:30.00Z corresponds to 2018-04-29T12:15:30+02:00 and the LocalDateTime from this OffsetDateTime gives you 2018-04-29T12:15:30; so does your LocalDateTime.now(c).

Demo:

import java.time.*;

public class Main {
    public static void main(String[] args) {
        Instant instant = Instant.parse("2018-04-29T10:15:30.00Z");
        ZoneId zoneId = ZoneId.of("Europe/Berlin");
        Clock c= Clock.fixed(instant, zoneId);

        // 2018-04-29T10:15:30.00Z corresponds to 2018-04-29T12:15:30+02:00
        OffsetDateTime odt = instant.atZone(zoneId).toOffsetDateTime();
        System.out.println(odt);

        // LocalDateTime from this OffsetDateTime results in 2018-04-29T12:15:30
        System.out.println(odt.toLocalDateTime());

        // So does LocalDateTime.now(c)
        System.out.println(LocalDateTime.now(c));
    }
}

Output:

2018-04-29T12:15:30+02:00
2018-04-29T12:15:30
2018-04-29T12:15:30

How to get your desired output?

You need to use the UTC offset to get the LocalDateTime with the same value as the given Instant.

Demo:

import java.time.*;

public class Main {
    public static void main(String[] args) {
        Clock c = Clock.fixed(Instant.parse("2018-04-29T10:15:30.00Z"), ZoneId.of("Europe/Berlin"));
        LocalDateTime ldt = Instant.now(c).atZone(ZoneOffset.UTC).toLocalDateTime();
        System.out.println(ldt);
    }
}

Output:

2018-04-29T10:15:30

Online Demo

Learn about the modern date-time API from Trail: Date Time.

like image 130
Arvind Kumar Avinash Avatar answered Oct 26 '25 05:10

Arvind Kumar Avinash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!