Linq to SQL DateTime values are local (Kind=Unspecified) - How do I make it UTC?

后端 未结 8 1867
萌比男神i
萌比男神i 2020-12-05 03:43

Isn\'t there a (simple) way to tell Linq To SQL classes that a particular DateTime property should be considered as UTC (i.e. having the Kind property of the DateTime type t

8条回答
  •  时光说笑
    2020-12-05 04:45

    SQL Server DateTime does not include any timezone or DateTimeKind information, therefore DateTime values retrieved from the database correctly have Kind = DateTimeKind.Unspecified.

    If you want to make these times UTC, you should 'convert' them as follows:

    DateTime utcDateTime = new DateTime(databaseDateTime.Ticks, DateTimeKind.Utc);
    

    or the equivalent:

    DateTime utcDateTime = DateTime.SpecifyKind(databaseDateTime, DateTimeKind.Utc);
    

    I assume your problem is that you are attempting to convert them as follows:

    DateTime utcDateTime = databaseDateTime.ToUniversalTime();
    

    This may appear reasonable at first glance, but according to the MSDN documentation for DateTime.ToUniversalTime, when converting a DateTime whose Kind is Unspecified:

    The current DateTime object is assumed to be a local time, and the conversion is performed as if Kind were Local.

    This behavior is necessary for backwards compatibility with .NET 1.x, which didn't have a DateTime.Kind property.

提交回复
热议问题