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

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

    The generated LinqToSql code provides extensibility points, so you can set values when the objects are loaded.

    The key is to create a partial class which extends the generated class, and then implement the OnLoaded partial method.

    For instance, let's say your class is Person, so you have a generated partial Person class in Blah.designer.cs.

    Extend the partial class by creating a new class (must be in a different file), as follows:

    public partial class Person {
    
      partial void OnLoaded() {
        this._BirthDate = DateTime.SpecifyKind(this._BirthDate, DateTimeKind.Utc);
      }
    }
    
    0 讨论(0)
  • 2020-12-05 04:50

    I you want UTC, TimeZone class can do it for you, if you want to convert between different timezones, than TimeZoneInfo is for you. exemple from my code with TimeZoneInfo:

    TimeZoneInfo cet = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
    ac.add_datetime = TimeZoneInfo.ConvertTime(DateTime.Now, cet);            
    
    0 讨论(0)
提交回复
热议问题