Skip to content
Advertisement

Why LocalDateTime formatted with zone offset?

Consider code:

public static void main(String[] args) {
  System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH")));
}

The output is 2022-05-04-17 while UTC time is 2022-05-04-10. The documentation says that LocalDateTime is without zone offset – so why there is 7 hour shift? (My local time zone is +7UTC)

Advertisement

Answer

You’ve called LocalDateTime.now(), which is documented as (emphasis mine):

Obtains the current date-time from the system clock in the default time-zone.

This will query the system clock in the default time-zone to obtain the current date-time.

The returned LocalDateTime doesn’t “know” the UTC offset, but it’s been applied already in determining the value.

If you want to get the current UTC time, you can use LocalDateTime.now(ZoneOffset.UTC). (It’s possible that LocalDateTime isn’t the most appropriate representation in that case though – we’d need to know more about what you’re using it for.)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement