Why doesn't DateTime.ToLocalTime () consider daylight saving time?

I have a UTC time string (which I get from the database, so I cannot change the format) created using DateTime.UtcNow.ToString("s"). I would like to show something custom like "10:00 AM". Where am I (in England), the clock has recently gone ahead, and the next method is the hour:

var timenowstring = DateTime.UtcNow.ToString("s");
var dateutc = DateTime.Parse(timenowstring).ToShortTimeString();
var datelocal = DateTime.Parse(timenowstring).ToLocalTime().ToShortTimeString();

Console.WriteLine("Utc time string: " + dateutc);
Console.WriteLine("Local time string: " + datelocal);

Both print "9:02 a.m." when in fact it is 10:02 a.m.

Here is a screenshot of its playback at http://csharppad.com/ :

utc and local show the same time - see system clock in lower right, which is correctlarger image

CSharpPad gist

What am I doing wrong and the easiest way to get a DateTime object that will return the correct time when I call .ToShortTimeString()?

NB docs in ToLocalTime () say:

, , DateTime.

+4
2

:

UTC ( , ), DateTime.UtcNow.ToString("s").

, . () . . SQL Server () datetime datetime2. . .NET, datetime. , .

, :

DateTime dt = Convert.ToDateTime(dataReader["myDateTimeField"].ToString());

. :

DateTime dt = (DateTime) dataReader["myDateTimeField"];

, NULL:

DateTime? dt = dataReader["myDateTimeField"] as DateTime;

, , . datetime DateTimeKind.Unspecified Kind, ToLocalTime , UTC. (. MSDN.)

, , ( ), - . ToLocalTime "" , . csharppad.com - UTC. , .

CSharpPad Time Zone

, ToLocalTime , , , . TimeZoneInfo :

// this uses the time zone for England
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTime englandDatetime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, tz);

open-source Noda Time, :

DateTimeZone tz = DateTimeZoneProviders.Tzdb["Europe/London"];
DateTime englandDateTime = Instant.FromDateTimeUtc(utcDateTime)
                                  .InZone(tz)
                                  .ToDateTimeUnspecified();
+7

, ( ). , http://csharppad.com, . : .

0

All Articles