Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format LocalDateTime with time zone offset

Tags:

java

java-8

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?

like image 813
Alexandr Avatar asked Jul 06 '16 15:07

Alexandr


2 Answers

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
like image 187
assylias Avatar answered Oct 04 '22 03:10

assylias


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!

like image 40
JGlass Avatar answered Oct 04 '22 04:10

JGlass