Coder Perfect

How can I retrieve an ISO 8601 date in string format from a DateTime object?




How can I get a string that is ISO 8601-compliant and reflects the same value?

It’s worth noting that ISO 8601 specifies a number of formats that are similar. I’m looking for the following format:


Asked by Iain

Solution #1


This gives you a date that looks like 2008-09-22T13:57:31.2311892-04:00 when you use custom date-time formatting.

Another way is:


It gives you 2008-09-22T14:01:54.9571247Z using the normal “round-trip” approach (ISO 8601).

You can use the following commands to get the desired format:


Answered by Wayne

Solution #2

Because the “s” format specifier is characterized as a sortable date/time pattern; adheres to ISO 8601, DateTime.UtcNow.ToString(“s”, System.Globalization.CultureInfo.InvariantCulture) should give you what you need.

EDIT: To get the additional Z at the end as the OP requires, use “o” instead of “s”.

Answered by Simon Wilson

Solution #3


Something along the lines of 2008-04-10T06:30:00

UtcNow obviously returns a UTC time so there is no harm in:

string.Concat(DateTime.UtcNow.ToString("s"), "Z")

Answered by Iain

Solution #4


private void TimeFormats()
    DateTime localTime = DateTime.Now;
    DateTime utcTime = DateTime.UtcNow;
    DateTimeOffset localTimeAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime));

    string strUtcTime_o = utcTime.ToString("o");
    string strUtcTime_s = utcTime.ToString("s");
    string strUtcTime_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

    string strLocalTimeAndOffset_o = localTimeAndOffset.ToString("o");
    string strLocalTimeAndOffset_s = localTimeAndOffset.ToString("s");
    string strLocalTimeAndOffset_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

    Response.Write("strUtcTime_o: " + strUtcTime_o + "<br/>");
    Response.Write("strUtcTime_s: " + strUtcTime_s + "<br/>");
    Response.Write("strUtcTime_custom: " + strUtcTime_custom + "<br/>");

    Response.Write("<br/>Local Time<br/>");
    Response.Write("strLocalTimeAndOffset_o: " + strLocalTimeAndOffset_o + "<br/>");
    Response.Write("strLocalTimeAndOffset_s: " + strLocalTimeAndOffset_s + "<br/>");
    Response.Write("strLocalTimeAndOffset_custom: " + strLocalTimeAndOffset_custom + "<br/>");

    strUtcTime_o: 2012-09-17T22:02:51.4021600Z
    strUtcTime_s: 2012-09-17T22:02:51
    strUtcTime_custom: 2012-09-17T22:02:51Z

Local Time
    strLocalTimeAndOffset_o: 2012-09-17T15:02:51.4021600-07:00
    strLocalTimeAndOffset_s: 2012-09-17T15:02:51
    strLocalTimeAndOffset_custom: 2012-09-17T22:02:51Z

Answered by Don

Solution #5



val it : string = "2013-10-13T13:03:50.2950037Z"

Answered by Henrik

Post is based on