Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current moment in ISO 8601 format with date, hour, and minute?

Tags:

java

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); `` 
like image 897
yegor256 Avatar asked Oct 12 '10 12:10

yegor256


People also ask

How can I get current date from ISO?

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.

What is current time in ISO format?

UTC time in ISO-8601 is 07:58:12Z.

How do I read the ISO 8601 date format?

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).


2 Answers

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.

like image 114
Joachim Sauer Avatar answered Sep 18 '22 13:09

Joachim Sauer


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)

like image 32
user85421 Avatar answered Sep 19 '22 13:09

user85421