I tried to add
format.setTimeZone(TimeZone.getTimeZone("UTC"));
when I saw the problem for the first time but it has no effect.
No matter what time-zone you add, the result will always end with Z
; nothing other than that (i.e. never Z02:00
as you have mentioned) until you add something else after that explicitly. The reason is that you are adding Z
as a literal ('Z'
) and therefore it will always be printed as Z
and nothing else.
Had your pattern been as follows:
yyyy-MM-dd'T'HH:mm:ssZ
the result would have been different for different timezone because in this pattern, Z
specifies Zone-Offset and not the literal, Z
(i.e. 'Z'
) e.g.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws InterruptedException {
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(format.format(Calendar.getInstance().getTime()));
format.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println(format.format(Calendar.getInstance().getTime()));
format.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
System.out.println(format.format(Calendar.getInstance().getTime()));
}
}
Output:
2020-09-02T21:15:36+0000
2020-09-02T22:15:36+0100
2020-09-03T02:45:36+0530
I recommend you switch from the outdated and error-prone java.util
date-time API and SimpleDateFormat
to the modern java.time
date-time API and the corresponding formatting API (package, java.time.format
). Learn more about the modern date-time API from Trail: Date Time.
Using modern date-time API:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) throws InterruptedException {
Instant instant = Instant.now();
// Printing default pattern (i.e. whatever Instant#toString returns)
System.out.println(instant);
// Get ZonedDateTime from Instant
ZonedDateTime zdt = instant.atZone(ZoneId.of("Etc/UTC"));
// Print custom formats
System.out.println(zdt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX")));
System.out.println(zdt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")));
System.out.println(zdt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssz")));
}
}
Output:
2020-09-02T21:30:36.770160Z
2020-09-02T21:30:36Z
2020-09-02T21:30:36+0000
2020-09-02T21:30:36UTC