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