EF - Save datetime with specific timezone in DB but read it as UTC

entity-framework entity-framework-6

Question

Is there a mapping configuration in Entity Framework where I can state to convert any datetime that i will be saving in the db to a specific timezone (eg CEST) and whenever I read it from DB, it should be converted to UTC?

1
0
6/24/2016 10:21:20 AM

Accepted Answer

Quick answer: No.

EF just moves the values back and forth.

Suggestion: just store UTC values in the database. If you need to recover the original timezone then store the original timezone as well (but note the common timezone abbreviations are often ambiguous).

Dates and times are hard to process in general, but most systems simply assume a single locale and ignore the issues.

3
6/24/2016 10:14:02 AM

Popular Answer

If you have to save datetime in a local zone, you can add a new property in your entity class for the UTC datetime. e.g.

public class MyEntity {
    public DateTime LocalDateTime {get; set;}

    //use this property in code instead of LocalDateTime.
    [NoMapped]
    public DateTime UtcDateTime {
        get { return /*convert LocalDateTime value to UTC */ }
        set { LocalDateTime = /*convert value to local zone */ }
    }
}

BTW, I didn't test this method. Just for your reference.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow