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

后端 未结 8 1866
萌比男神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:34

    This code snippet will allow you to convert the DateTimes (Kind=Unspecified) you get back from LINQ to SQL into UTC times without the times being affected.

    TimeZoneInfo UTCTimeZone = TimeZoneInfo.FindSystemTimeZoneById("UTC");
    DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(myLinq2SQLTime, UTCTimeZone);
    

    There are probably cleaner ways to do this but I had this to hand and could test it quickly!

    I am not sure if there is a way to get it working with LINQ to SQL classes transparently - you might want to look in the partial class and see if you can hook where the values are read/written.

提交回复
热议问题