Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does DateTime.Now.ToString("u") not work?

I am currently in British summer time which is UTC +1 Hour. I confirmed my PC is correct with the following code and it returns true.

System.TimeZone.CurrentTimeZone.IsDaylightSavingTime(Date.Now)

My question is then why does the UTC formatter not work as I would expect:

DateTime.Now.ToString("u")

It returns the exact current system date as below in UTC format as expected but with the Z (Zulu Time) at the end not +01:00?

i.e.

2009-05-27 14:21:22Z

not

2009-05-27 14:21:22+01:00

Is this correct functionality?

like image 795
John Avatar asked May 27 '09 13:05

John


People also ask

How do I change the date format in ToString?

To do this, you use the "MM/yyyy" format string. The format string uses the current culture's date separator. Getting a string that contains the date and time in a specific format. For example, the "MM/dd/yyyyHH:mm" format string displays the date and time string in a fixed format such as "19//03//2013 18:06".

How accurate is DateTime now in C#?

From MSDN you'll find that DateTime. Now has an approximate resolution of 10 milliseconds on all NT operating systems. The actual precision is hardware dependent.


2 Answers

MSDN states the following:

Represents a custom date and time format string defined by the DateTimeFormatInfo.UniversalSortableDateTimePattern property. The pattern reflects a defined standard and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'".

When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.

Formatting does not convert the time zone for the date and time object. Therefore, the application must convert a date and time to Coordinated Universal Time (UTC) before using this format specifier.

You should use the following code to convert your current Date to UTC before formatting it:

DateTime.UtcNow.ToString("u")

or

DateTime.Now.ToUniversalTime().ToString("u")

To display in the format you expected (i.e. 2009-05-27 14:21:22+01:00), you would need to use a custom date format:

DateTime.Now.ToString("yyyy-MM-dd HH:mm:sszzz");
like image 61
Patrick McDonald Avatar answered Oct 19 '22 10:10

Patrick McDonald


You need to use DateTime.Now.ToUniversalTime().ToString("u").

like image 32
Badaro Avatar answered Oct 19 '22 09:10

Badaro