Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the current time and date in ISO date format in java?

I am supposed to send the current date and time in ISO format as given below:

'2018-02-09T13:30:00.000-05:00'

I have written the following code:

Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.000'Z'");
System.out.println(formatter.format(date));
System.out.println(formatter1.format(date));

It prints in the following way:

2018-04-30T12:02
2018-04-30T12:02:58.000Z

But it is not printing as the format mentioned above. How can I get the -5:00 as shown in the format and what does it indicate?

like image 785
azaveri7 Avatar asked Apr 30 '18 06:04

azaveri7


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.

How do I convert date and time to ISO?

The date. toISOString() method is used to convert the given date object's contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ).

What is ISO 8601 date format Java?

The Date/Time API in Java works with the ISO 8601 format by default, which is (yyyy-MM-dd) . All Dates by default follow this format, and all Strings that are converted must follow it if you're using the default formatter.


1 Answers

In java 8 you can use the new java.time api:

OffsetDateTime now = OffsetDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
System.out.println(formatter.format(now)); // e.g. 2018-04-30T08:43:41.4746758+02:00

The above uses the standard ISO data time formatter. You can also truncate to milliseconds with:

OffsetDateTime now = OffsetDateTime.now().truncatedTo(ChronoUnit.MILLIS);

Which yields something like (only 3 digits after the dot):

2018-04-30T08:54:54.238+02:00
like image 161
Jorn Vernee Avatar answered Sep 22 '22 09:09

Jorn Vernee