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)

1 answer

  • answered 2022-05-04 10:58 Jon Skeet

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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum