简体   繁体   中英

How to format LocalDateTime with time zone offset

I tried to do it like this:

    ZoneOffset zoneOffset = ZoneOffset.ofHours(3);
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("HH:mm:ss");

    LocalDateTime dateTime = LocalDateTime.now();
    System.out.println("dateTimeWithoutOffset: " + fmt.format(dateTime));

    ZonedDateTime zonedDateTime = ZonedDateTime.of(dateTime, zoneOffset);
    System.out.println("dateWithOffset: " + fmt.format(zonedDateTime));

But I get the same output:

dateTimeWithoutOffset: 18:11:06
dateTimeWithOffset: 18:11:06

I want to see something like this:

dateTimeWithoutOffset: 18:11:06
dateTimeWithOffset: 21:11:06

What am I doing wrong?

If you want to work with a zone offset, an OffsetDateTime would make more sense than a ZonedDateTime .

And to apply the offset to your local time, one way is to say that the time is in UTC and you want the local time in a different time zone. So it could look like:

OffsetDateTime timeUtc = dateTime.atOffset(ZoneOffset.UTC); //18:11:06 UTC
OffsetDateTime offsetTime = timeUtc.withOffsetSameInstant(zoneOffset); //21:11:06 +03:00
System.out.println("dateWithOffset: " + fmt.format(offsetTime)); //21:11:06

Because I was trying to do the opposite, and hunting around and came across this question, I used this to convert the date on the server (UTC) to -7 hours Phoenix, AZ USA time
Note: the server was UTC

LocalDateTime date = LocalDateTime.now(ZoneOffset.ofHours(-7));
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy:HH:mm:ss");
String myDate = date.format(dtf);

Hope it helps anyone else in a similar scenario!

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