I been looking for this answer but I could be mistaken as to how to implement this. I have a ZonedDateTime variable and currently if I were to print it it would print for example 2017-12-03T10:15:30+01:00. is there any way to print the time with the off set already added or subtracted? for example I would like to see with the example above 16:30. Thank you for your help!
ZonedDateTime#withZoneSameInstant
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String dateTimeStr = "2017-12-03T10:15:30+01:00";
ZonedDateTime zdtGiven = ZonedDateTime.parse(dateTimeStr);
System.out.println(zdtGiven);
// Date-time adjusted with Zone-Offset (i.e. date-time at UTC)
ZonedDateTime zdtAtUTC = zdtGiven.withZoneSameInstant(ZoneId.of("Etc/UTC"));
System.out.println(zdtAtUTC);
// Alternatively,
OffsetDateTime odtAtUTC = zdtGiven.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(odtAtUTC);
// Custom format
String formattedDateTimeStr = zdtAtUTC.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss"));
System.out.println(formattedDateTimeStr);
}
}
Output:
2017-12-03T10:15:30+01:00
2017-12-03T09:15:30Z[Etc/UTC]
2017-12-03T09:15:30Z
2017-12-03T09:15:30
The +01:00
in the date-time string, 2017-12-03T10:15:30+01:00
means that the date & time in the string has been already adjusted by adding +01:00
hour to the date & time at UTC
. It means if you want to remove the +01:00
from it, +01:00
hour needs to be subtracted from 2017-12-03T10:15:30
i.e. it will become 2017-12-03T09:15:30
representing the date & time at UTC
.