To format a java.util.Date
as an ISO8601 timestamp including the correct timezone, java.time.OffsetDateTime
can be used.
package de.lhorn.playground; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Date; import java.util.TimeZone; public class FormatDatetimeExample { public static void main(String[] args) { // The Date we want to format. Date date = new Date(); long millis = date.getTime(); // The local timezone of the system we run this code on. TimeZone timeZone = TimeZone.getDefault(); // We calculate the timezone offset that applies to the given Date. int offset = timeZone.getOffset(millis); ZoneOffset zoneOffset = ZoneOffset.ofTotalSeconds(offset / 1_000); // Convert the Date into an OffsetDateTime using the calculated ZoneOffset. Instant instant = date.toInstant(); OffsetDateTime odt = instant.atOffset(zoneOffset); // The output is something like "2019-10-30T08:16:39.535+01:00" which // includes the correct timezone in which I am currently located (Europe/Berlin). System.out.println("odt: " + odt.toString()); } }