C# - Formatting current time

28,124

Solution 1

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

Solution 2

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.

Solution 3

You can try either:

DateTime.Now.ToString("o");

which also includes the timezone component. - OR -

DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffffff")

Solution 4

Try this:

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

and check out this msdn link

Share:
28,124
PercivalMcGullicuddy
Author by

PercivalMcGullicuddy

Updated on July 09, 2022

Comments

  • PercivalMcGullicuddy
    PercivalMcGullicuddy almost 2 years

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

  • Christopher Currens
    Christopher Currens over 12 years
    His wanted a Z put on the end.
  • Dave Walker
    Dave Walker over 12 years
    Oh sorry that is what I meant - that is why I gave you the +1. I didn't know why he wnated a Z.
  • Gabe
    Gabe over 12 years
    @rangitatanz: The Z (I believe derived from "zero hour") means that it is UTC time, so it should actually be DateTime.UtcNow.
  • Gabe
    Gabe over 12 years
    You'll notice that stackoverflow.com also puts a Z at the end of their timestamps.