Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why LocalDateTime formatted with zone offset?

Tags:

java

java-time

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)

like image 412
Cherry Avatar asked Dec 29 '25 16:12

Cherry


1 Answers

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

like image 189
Jon Skeet Avatar answered Jan 01 '26 07:01

Jon Skeet



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!