Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create .NET CultureInfo with Dateformat ISO 8601?

Is it possible to make .NET create the following output?

DateTime.UtcNow.ToString() --> "2017-11-07T00:40:00.123456Z"

Of course there is always the possibility to use ToString("s") or ToString("yyyy-MM-ddTHH:mm:ss.fffffffK"). But is there a way to adjust the default-behaviour for the parameterless ToString-Method to the desired output?

I tried changing the CurrentCulture. But the best I got was "2017-11-07 00:40:00.123456Z". I did not find a way to change the separator between the date and the time from a space to "T".

like image 414
Andreas Avatar asked Nov 06 '17 23:11

Andreas


People also ask

How do I format a date in ISO 8601?

ISO 8601 Formats 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).

How do I convert DateTime to ISO 8601?

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 object is created using date() constructor.

How do I change the default date format in C#?

var ci = new CultureInfo("en-US"); ci. DateTimeFormat. ShortDatePattern = "MM/dd/yyyy"; app.

What is ISO date format C#?

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.


1 Answers

It is possible, but only by accessing an internal field via reflection, which is not guaranteed to work in all cases.

var culture = (CultureInfo) CultureInfo.InvariantCulture.Clone();
var field = typeof(DateTimeFormatInfo).GetField("generalLongTimePattern",
                                           BindingFlags.NonPublic | BindingFlags.Instance);
if (field != null)
{
    // we found the internal field, set it
    field.SetValue(culture.DateTimeFormat, "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK");
}
else
{
    // fallback to setting the separate date and time patterns
    culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
    culture.DateTimeFormat.LongTimePattern = "HH:mm:ss.FFFFFFFK";
}
CultureInfo.CurrentCulture = culture;

Console.WriteLine(DateTime.UtcNow);  // "2017-11-07T00:53:36.6922843Z"

Note that the ISO 8601 spec does allow a space to be used instead of a T. It's just preferable to use the T.

like image 171
Matt Johnson-Pint Avatar answered Sep 19 '22 21:09

Matt Johnson-Pint