'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)



Solution 1:[1]

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.)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jon Skeet