C# - Formatting current time

PercivalMcGullicuddy picture PercivalMcGullicuddy · Oct 13, 2011 · Viewed 25.6k times · Source

In C#, how can I get the current DateTime in the following format? 2011-08-10T21:36:01.6327538Z

Answer

Christopher Currens picture Christopher Currens · Oct 13, 2011
DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ")

Keep in mind that DateTime.Now is sometimes only precise to a thousandth of a second, depending on the system clock. This page shows the following:

It is possible to display very small fractional units of a second, such as ten thousandths of a second or hundred-thousandths of a second. However, these values may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.

However, if you populate the DateTime yourself, you can make it more precise. I am not aware of any other built-in libraries that are more precise than DateTime.UtcNow.

Also, DateTime.UtcNow.ToString("o") will give you an ordinal datetime string. This doesn't specify the timezone at the end, so you'd still need to add Z to the end if you were dealing with Utc