How to format LocalDateTime with time zone offset

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!


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

Tags:

Java

Java 8