This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

This article, the original problem: translate for stackoverflow question stackoverflow.com/questions/3…

Issue an overview

What is the most elegant way to get an ISO 8601 representation of the current UTC moment? It should look something like: 2010-10-12T08:50Z.

Example:

String iso8601 = DateFormat.getDateTimeInstance(DateFormat.ISO_8601).format(date);
Copy the code

Best answer

Format any Date objects you need with SimpleDateFormat:

TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
Copy the code

Using the new Date () as shown above will format the current time.

Other answer

1.

For systems where the default time zone is not UTC:

TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
Copy the code

You can declare an instance of SimpleDateFormat as a global constant if you often need to, but note that this class is not thread-safe. If accessed by multiple threads at the same time, synchronization must occur. Edit: If I’m going to do a lot of different time/date operations, I’d like georda time… EDIT2: Corrected: setTimeZone does not accept strings (corrected by Paul)

2.

Since Java 8, ava.time has become very simple and thread-safe.

Zoneddatetime.now (zoneoffset.utc).format(datetimeFormatter.iso_instant)2015-04- 14 t11:07:36.Java ZonedDateTime.now(zoneid.of ("Europe/Paris" ) )
             .truncatedTo( ChronoUnit.MINUTES )
             .format( DateTimeFormatter.ISO_DATE_TIME )
Copy the code

Results: 2015-04-14T11:07:00 + 01:00 [Europe/Paris]