Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can obtain a string representation of an ISO 8601 date from a DateTime object using the ToString() method with the "s" format specifier. This will return the date and time in the following format: "yyyy-MM-ddTHH:mm:ss" where "T" is the separator between the date and time.

For example:

DateTime now = DateTime.Now;
string isoDate = now.ToString("s");
Console.WriteLine(isoDate);

Output:

2021-07-06T10:46:23

If you want to include the time zone offset, you can use the "o" format specifier instead:

string isoDateWithOffset = now.ToString("o");
Console.WriteLine(isoDateWithOffset);

Output:

2021-07-06T10:46:23.6759678-04:00