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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With