How to convert a date to UTC properly and then convert it back?

后端 未结 5 2044
心在旅途
心在旅途 2021-02-13 19:48

I\'m struggling with converting DateTime to UTC, the concept and all, something I\'m not understanding correctly.

When I get a date time string, say \"7/10/2013\", I si

5条回答
  •  梦毁少年i
    2021-02-13 20:28

    If you want to store a local time in your database as UTC, you need to first convert it to universal time:

     DateTime dbDateTime = localDateTime.ToUniversalTime();
     ... store dbDateTime in the database ...
    

    When you read it back from the database, it will have its Kind property set to Unspecified. You will need to explicitly set its Kind property to UTC:

    dbDateTime = ... get from database, e.g. (DateTime) reader["SomeDateTimeColumn"]
    dbDateTime = DateTime.SpecifyKind(dbDateTime, DateTimeKind.Utc);
    

    If you then want to convert it to local time, you can use:

    DateTime localDateTime = dbDateTime.ToLocalTime();
    

提交回复
热议问题