20

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

PercivalMcGullicuddy
  • 5,263
  • 9
  • 46
  • 65
  • 1
    just a note, I dont think that it will do Zulu time notation. i.e. it wont add the "Z" and convert to UTC/GMT (I could be wrong, in which case, stop reading). If your time is already in UTC/GMT then you can just add the "Z" after. Alternatively, if you wanted a universal timestamp but did not want to convert a local time, you can use the "zzz" key to print the offset from UTC which is a commonly accepted universal date notation. – gnomed Oct 13 '11 at 00:10

5 Answers5

31
DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ")

Note that if you're not using DateTime.UtcNow and are instead using an existing DateTime instance, you may need to convert it to universal time before using the given format string (e.g. DateTime.ToUniversalTime())

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 always specify the timezone at the end, so you'd still need to add Z to the end if you knew were dealing with Utc and the DateTime format was Unspecified

Christopher Currens
  • 29,917
  • 5
  • 57
  • 77
  • You'll notice that stackoverflow.com also puts a `Z` at the end of their timestamps. – Gabe Oct 13 '11 at 00:59
  • @ANeves It could probably be clarified in my answer, but the only time I append Z is when it is from DateTime.UtcNow (so the date is guaranteed to be UTC time). And at the end of the answer I only mention appending Z if you were dealing with Utc, not for a local timezone. From your comment, it appears that it's possible that people may not get the sense of it, so I'll update it to make it clearer. – Christopher Currens Dec 28 '22 at 14:08
  • 1
    Thanks, that's much better! <3 (Typo: change "if knew" to "if you knew", at the end of the answer.) – ANeves Dec 30 '22 at 00:01
4

If you want your times in UTC (which is what the Z implies) then you need to ensure that they are UTC times...

i.e.

DateTime.UtcNow.ToString("O");

or assuming that you know that your datetime is local...

DateTime foo = MethodThatReturnsALocalTime();
foo.ToUniversalTime().ToString("O");

FWIW: DateTime.UtcNow is faster than DateTime.Now because it doesn't need to do a timezone lookup, on Compact Framework that difference can be very noticeable for some reason.

Paul Roberts
  • 341
  • 2
  • 5
1

Try this:

    var xs = DateIime.Now;
    var frmtdDatetime = xs.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff");

and check out this msdn link

Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
1

You can try either:

DateTime.Now.ToString("o");

which also includes the timezone component. - OR -

DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffffff")
Paul Walls
  • 5,884
  • 2
  • 22
  • 23
0

You want a date in ISO 8601 format.

Use the "O" round-trip format with a date in UTC:

// 2022-12-22T10:20:30.4567890Z
string formatted = DateTime.UtcNow.ToString("O");

If your DateTime is not marked as UTC, the round-trip format is still round-trip but the date won't have the Z at the end:

// 2022-12-22T10:20:30.4567890Z+09:00
string local = DateTime.Now.ToString("O");
// 2022-12-22T10:20:30.4567890Z
string unspecified = new DateTime(2022, 12, 24, 0, 0, 0, DateTimeKind.Unspecified).ToString("O");

We see that local times add a time offset instead of a Z, and Unspecified times cannot add any information on time offset.

This is where problems start. Don't just add a Z at the end!

Pitfall

But why can't we just add a Z at the end?
Because 10h:20m:30s local is not the same as 10h:20m:30s UTC.

Let's assume we are in Japan.
If a date is local, 11:00:00AM is actually 02:00:00Z and not 11:00:00Z.

Let's see how bad data can interfere:

long ticks = 638074368000000000L;
var utc = new DateTime(ticks, DateTimeKind.Utc);
var local = new DateTime(ticks, DateTimeKind.Local);
var unspecified = new DateTime(ticks, DateTimeKind.Unspecified);
var utcAsLocal = utc.ToLocalTime();
var localAsUtc = new DateTime(ticks, DateTimeKind.Local);
var localFromLocalClock = new DateTime(2022, 12, 24, 9, 0, 0, DateTimeKind.Local);
var utcFromLocalClock = localFromLocalClock.ToUniversalTime();
Console.WriteLine($"UTC:         {utc:O}");            // 1 OK: 2022-12-24T00:00:00.0000000Z
Console.WriteLine($"Local:       {local:O}");          // 2 ??: 2022-12-24T00:00:00.0000000+09:00
Console.WriteLine($"Unspecified: {unspecified:O}");    // 3 OK: 2022-12-24T00:00:00.0000000
Console.WriteLine($"UTC>Local:   {utcAsLocal:O}");     // 4 OK: 2022-12-24T09:00:00.0000000+09:00
Console.WriteLine($"Local>Utc:   {localAsUtc:O}");     // 5 ??: 2022-12-24T00:00:00.0000000+09:00
Console.WriteLine($"!Local: {localFromLocalClock:O}"); // 6 OK: 2022-12-24T09:00:00.0000000+09:00
Console.WriteLine($"!UTC:     {utcFromLocalClock:O}"); // 7 OK: 2022-12-24T00:00:00.0000000Z

Notice that the local date does not represent the same universal instant as the UTC and Unspecified datetimes! Lines 2 and 5 are actually different instants.
The localFromLocalClock does.

So if we get a date that is not in UTC and just format it either without timezone or adding a Z, we're corrupting the data.

We often become vulnerable to bugs due to this. We should be careful when manipulating dates.
This is why your UTC requirement for the date is important.

Suggested reading

The Noda Time API was built (by Jon Skeet!) to deal with this.

It presents a good set of data structures that ensure that we work with dates correctly.

ANeves
  • 6,219
  • 3
  • 39
  • 63