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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With