The java.util.Date toString() method displays the date in the local time zone.
There are several common scenarios where we want the data to be printed in UTC, including logs, data export and communication with external programs.
- What’s the best way to create a String representation of
java.util.Datein UTC? - How to replace the j.u.Date’s
toString()format, which isn’t sortable (thanks, @JonSkeet!) with a better format?
Addendum
I think that the standard way of printing the date in a custom format and time zone is quite tedious:
final Date date = new Date();
final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT);
final TimeZone utc = TimeZone.getTimeZone("UTC");
sdf.setTimeZone(utc);
System.out.println(sdf.format(date));
I was looking for a one-liner like:
System.out.println(prettyPrint(date, "yyyy-MM-dd'T'HH:mm:ss.SSS zzz", "UTC"));
Following the useful comments, I’ve completely rebuilt the date formatter. Usage is supposed to:
If you consider this code useful, I may publish the source and a JAR in github.
Usage
Code
(This code is also the subject of a question on Code Review stackexchange)