What is the most elegant way to get ISO 8601 formatted presentation of the current moment, UTC? It should look like: 2010-10-12T08:50Z
.
Example:
String d = DateFormat.getDateTimeInstance(DateFormat.ISO_8601).format(date); ``
Use the Date. toISOString() Method to Get Current Date in JavaScript. This method is used to return the date and time in ISO 8601 format. It usually returns the output in 24 characters long format such as YYYY-MM-DDTHH:mm:ss.
UTC time in ISO-8601 is 07:58:12Z.
ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).
Use SimpleDateFormat
to format any Date
object you want:
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());
Using a new Date()
as shown above will format the current time.
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());
The SimpleDateFormat
instance may be declared as a global constant if needed frequently, but beware that this class is not thread-safe. It must be synchronized if accessed concurrently by multiple threads.
EDIT: I would prefer Joda Time if doing many different Times/Date manipulations...
EDIT2: corrected: setTimeZone
does not accept a String (corrected by Paul)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With