简体   繁体   中英

How to format ZonedDateTime

I'm trying to take a datetime stored as UTC and convert it to a datetime in a given timezone. The ZonedDateTime is correct as far as I know ('America/Chicago' is 5 hours behind UTC) but DateTimeFormatter is not taking the offset into account when formatting the datetime.

My wall clock time: 12:03 pm

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a")
LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);
ZonedDateTime zonedDateTime = now.atZone(ZoneId.of("America/Chicago"));

log.info("Now: " + now);
log.info("Zoned date time: " + zonedDateTime);
log.info("Formatted date time: " + zonedDateTime.format(formatter));

Output:

Now: 2019-08-29T17:03:10.041
Zoned date time: 2019-08-29T17:03:10.041-05:00[America/Chicago]
Formatted date time: 08/29/2019 05:03 PM

The formatted time I'm expecting: 08/29/2019 12:03 PM

LocalDateTime is a date/time without a timezone. So, what you've done is taken a UTC datetime and then used .atZone to tell Java that this date/time is actually in America/Chicago time rather than converting it to be in the correct time zone.

What you should have done is something like this:

ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime zonedDateTime = now.withZoneSameInstant(ZoneId.of("America/Chicago"));

log.info("Now: " + now);
log.info("Zoned date time: " + zonedDateTime);
log.info("Formatted date time: " + zonedDateTime.format(formatter));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM