Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 timezone conversions

In Java 8, I want to convert a datetime from UTC to ACST (UTC+9:30).

input -> 2014-09-14T17:00:00+00:00

output-> 2014-09-15 02:30:00

String isoDateTime = "2014-09-14T17:00:00+00:00";
LocalDateTime fromIsoDate = LocalDateTime.parse(isoDateTime, DateTimeFormatter.ISO_OFFSET_DATE_TIME);

ZoneOffset offset = ZoneOffset.of("+09:30");
OffsetDateTime acst = OffsetDateTime.of(fromIsoDate, offset);
System.out.println(acst.toString()); // 2014-09-14T17:00+09:30
System.out.println(acst.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); // 2014-09-14T17:00:00+09:30

Why is the offset not performed?

like image 938
Javide Avatar asked Sep 17 '14 08:09

Javide


2 Answers

Try:

String isoDateTime = "2014-09-14T17:00:00+00:00";
ZonedDateTime fromIsoDate = ZonedDateTime.parse(isoDateTime);
ZoneOffset offset = ZoneOffset.of("+09:30");
ZonedDateTime acst = fromIsoDate.withZoneSameInstant(offset);

System.out.println("Input:  " + fromIsoDate);
System.out.println("Output: " + acst.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); 

Output:

Input:  2014-09-14T17:00Z
Output: 2014-09-15T02:30:00+09:30

Using OffsetDateTime

While it is generally better to use ZonedDateTime as shown above, you can perform the same conversion using OffsetDateTime as follows:

String isoDateTime = "2014-09-14T17:00:00+00:00";
OffsetDateTime fromIsoDate = OffsetDateTime.parse(isoDateTime);
ZoneOffset offset = ZoneOffset.of("+09:30");
OffsetDateTime acst = fromIsoDate.withOffsetSameInstant(offset);
like image 116
aioobe Avatar answered Oct 21 '22 00:10

aioobe


Slight improvement on the above. Avoids hardcoding offset. Also, takes care of daylight savings.

public static LocalDateTime convertTo(LocalDateTime dateTime, String timeZone) {
    ZoneId zone = ZoneId.of(timeZone);
    ZonedDateTime zdt = dateTime.atZone(zone);
    ZoneOffset offset = zdt.getOffset();
    return dateTime.plus(offset.getTotalSeconds(), ChronoUnit.SECONDS);
}
like image 36
bsandhu Avatar answered Oct 21 '22 01:10

bsandhu