how to convert date string to iso8601 standard?

  • Last Update :
  • Techknowledgy :
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String string1 = "2001-07-04T12:08:56.235-0700";
Date result1 = df1.parse(string1);

DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String string2 = "2001-07-04T12:08:56.235-07:00";
Date result2 = df2.parse(string2);

Ended up implementing this simple class. It covers only the most common form of ISO 8601 strings, but this should be enough in some cases (when you're quite sure that the input will be in this format).

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Helper class for handling a most common subset of ISO 8601 strings
 * (in the following format: "2008-03-01T13:00:00+01:00"). It supports
 * parsing the "Z" timezone, but many other less-used features are
 * missing.
 */
public final class ISO8601 {
   /** Transform Calendar to ISO 8601 string. */
   public static String fromCalendar(final Calendar calendar) {
      Date date = calendar.getTime();
      String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
         .format(date);
      return formatted.substring(0, 22) + ":" + formatted.substring(22);
   }

   /** Get current date and time formatted as ISO 8601 string. */
   public static String now() {
      return fromCalendar(GregorianCalendar.getInstance());
   }

   /** Transform ISO 8601 string to Calendar. */
   public static Calendar toCalendar(final String iso8601string)
   throws ParseException {
      Calendar calendar = GregorianCalendar.getInstance();
      String s = iso8601string.replace("Z", "+00:00");
      try {
         s = s.substring(0, 22) + s.substring(23); // to get rid of the ":"
      } catch (IndexOutOfBoundsException e) {
         throw new ParseException("Invalid length", 0);
      }
      Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
      calendar.setTime(date);
      return calendar;
   }
}

If you know the input is in UTC, such as the Z (for Zulu) on the end, the Instant class can parse.

java.util.Date date = Date.from(Instant.parse("2014-12-12T10:39:40Z"));

If your input may be another offset-from-UTC values rather than UTC indicated by the Z (Zulu) on the end, use the OffsetDateTime class to parse.

OffsetDateTime odt = OffsetDateTime.parse("2010-01-01T12:00:00+01:00");

Then extract an Instant, and convert to a java.util.Date by calling from.

Instant instant = odt.toInstant(); // Instant is always in UTC.
java.util.Date date = java.util.Date.from(instant);

tl;dr

OffsetDateTime.parse("2010-01-01T12:00:00+01:00")

The OffsetDateTime class represents a moment on the timeline with an offset-from-UTC but not a time zone.

OffsetDateTime odt = OffsetDateTime.parse("2010-01-01T12:00:00+01:00");

To see the same value through the lens of UTC, extract an Instant or adjust the offset from +01:00 to 00:00.

Instant instant = odt.toInstant();

Adjust into a time zone if desired. A time zone is a history of offset-from-UTC values for a region, with a set of rules for handling anomalies such as Daylight Saving Time (DST). So apply a time zone rather than a mere offset whenever possible.

ZonedDateTime zonedDateTimeMontréal = odt.atZoneSameInstant(ZoneId.of("America/Montreal"));

For a date-only value, use LocalDate.

LocalDate ld = LocalDate.of(2010, Month.JANUARY, 1);

The Jackson-databind library also has ISO8601DateFormat class that does that (actual implementation in ISO8601Utils.

ISO8601DateFormat df = new ISO8601DateFormat();
Date d = df.parse("2010-07-28T22:25:51Z");

Starting from Java 8, there is a completely new officially supported way to do this:

    String s = "2020-02-13T18:51:09.840Z";
    TemporalAccessor ta = DateTimeFormatter.ISO_INSTANT.parse(s);
    Instant i = Instant.from(ta);
    Date d = Date.from(i);

Suggestion : 2

Last modified: Aug 15, 2022, by MDN contributors

toISOString()
const today = new Date('05 October 2011 14:48 UTC');

console.log(today.toISOString()); // Returns 2011-10-05T14:48:00.000Z

Suggestion : 3

Feb 16, 2017

2017 - 02 - 16 T20: 22: 28 + 00: 00
2017 - 02 - 16 T20: 22: 28.000 + 00: 00
// Input
Date date = new Date(System.currentTimeMillis());

// Conversion
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
sdf.setTimeZone(TimeZone.getTimeZone("CET"));
String text = sdf.format(date);

// Output
// "2017-02-16T21:00:00.000+01:00"
// Input
Calendar calendar = Calendar.getInstance();
calendar.set(2017, Calendar.FEBRUARY, 16, 20, 22, 28);
calendar.set(Calendar.MILLISECOND, 0);
Date date = calendar.getTime();

// Conversion
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
sdf.setTimeZone(TimeZone.getTimeZone("CET"));
String text = sdf.format(date);

// Output
// "2017-02-16T20:22:28.000+01:00"
// Input
GregorianCalendar calendar;
calendar = new GregorianCalendar(2017, Calendar.FEBRUARY, 16, 20, 22, 28);
Date date = calendar.getTime();

// Conversion
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
sdf.setTimeZone(TimeZone.getTimeZone("CET"));
String text = sdf.format(date);

// Output
// "2017-02-16T20:22:28.000+01:00"
// Input
ZonedDateTime d = LocalDate
   .of(2017, 2, 16)
   .atTime(20, 22, 28)
   .atZone(ZoneId.of("CET"));

// Conversion
String text = DateTimeFormatter.ISO_DATE_TIME.format(d);

// Output
// "2017-02-16T20:22:28+01:00[CET]"
// Conversion
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(d);

// Output
// "2017-02-16T20:22:28.000+01:00"

Suggestion : 4

To get an ISO 8601 date in string format in Python 3, you can simply use the isoformat function. It returns the date in the ISO 8601 format. For example, if you give it the date 31/12/2017, it'll give you the string '2017-12-31T00:00:00'. ,In older python versions, you can use the strftime function to format the datetime object such that you get the desired result. ,How do I format a string using a dictionary in Python 3?,How do I do a case insensitive string comparison in Python?

You can use it as follows −

from datetime
import datetime
my_date = datetime.now()
print(my_date.isoformat())

This will give the output −

2018 - 01 - 02 T22: 08: 12.510696

example

from datetime
import datetime
my_date = datetime.now()
print(my_date.strftime('%Y-%m-%dT%H:%M:%S.%f%z'))

Suggestion : 5

Last updated: Jul 25, 2022

Copied!
   const dateStr = '2022-07-21';

const date = new Date(dateStr);

const iso = date.toISOString();
console.log(iso); // 👉️ "2022-07-21T00:00:00.000Z"
Copied!
   const dateStr = '2022-07-21';

const isoStr = dateStr + 'T00:00:00.000Z';
console.log(isoStr); // 👉️ "2022-07-21T00:00:00.000Z"
Copied! // 👇️ formatted as m/d/yyyy
   const dateStr = '7/24/2022';

function padTo2Digits(num) {
   return num.toString().padStart(2, '0');
}

const [month, date, year] = dateStr.split('/');

const isoStr = `${year}-${padTo2Digits(month)}-${padTo2Digits(
  date,
)}T00:00:00.000Z`;

console.log(isoStr); // 👉️ "2022-07-24T00:00:00.000Z"

Suggestion : 6

Posted by Ahsan Ullah | Updated Date Jun 8, 2022 | 0

To begin, let’s update our Program class and declare two DateTime objects, one local and another as a UTC standard type:

var localTime = new DateTime(2022, 1, 13, 16, 25, 35, 125, DateTimeKind.Local);
var utcTime = new DateTime(2022, 1, 13, 16, 25, 35, 125, DateTimeKind.Utc);

The sortable format specifier (“s“) is useful to get an ISO 8601 compliant sortable string:

Console.WriteLine($ "Local: {localTime.ToString("
   s ")}"); // 2022-01-13T16:25:35
Console.WriteLine($ "UTC: {utcTime.ToString("
   s ")}"); // 2022-01-13T16:25:35

The round-trip format specifier (“o“) is useful to get an ISO 8601 string which includes time-zone information:

Console.WriteLine($ "Local: {localTime.ToString("
   o ")}"); // 2022-01-13T16:25:35.1250000+06:00
Console.WriteLine($ "UTC: {utcTime.ToString("
   o ")}"); // 2022-01-13T16:25:35.1250000Z

In this method, we convert the date to UTC value and then format it using ToString("u"). Furthermore, we replace whitespace with “T“. This is because ISO 8601 does not allow whitespace as the date-time separator but expects “T” instead. So, we have our extension method ready for standard ISO 8601 compliant UTC output:

Console.WriteLine($ "Local: {localTime.ToUniversalIso8601()}"); // 2022-01-13T10:25:35Z
Console.WriteLine($ "UTC: {utcTime.ToUniversalIso8601()}"); // 2022-01-13T16:25:35Z

In contrast, ‘z’ and ‘K’ are purely C# formatting literals that add time zone information based on the DateTimeKind value associated with the DateTime object. While ‘K‘ provides full time-zone phrase, ‘z‘ offers flexibility to print in a short phrase:

var format = "yyyy-MM-ddTHH:mm:ssK";
var unspecified = new DateTime(2022, 1, 13, 16, 25, 30, DateTimeKind.Unspecified);
var utc = new DateTime(2022, 1, 13, 16, 25, 30, DateTimeKind.Utc);
var local = new DateTime(2022, 1, 13, 16, 25, 30, DateTimeKind.Local);

Console.WriteLine(unspecified.ToString(format)); // 2022-01-13T16:25:30
Console.WriteLine(utc.ToString(format)); // 2022-01-13T16:25:30Z
Console.WriteLine(local.ToString(format)); // 2022-01-13T16:25:30+06:00
Console.WriteLine(local.ToString("yyyy-MM-ddTHH:mm:sszz")); // 2022-01-13T16:25:30+06

Suggestion : 7

Post date March 27, 2021

For instance, we can write:

console.log(moment(new Date(2021, 1, 1)).toISOString())

Then we get:

'2021-02-01T08:00:00.000Z'

Then the console log logs:

'2021-02-01T00:00:00.000-08:00'