Converting UTC DateTime to local DateTime

前端 未结 4 1625
终归单人心
终归单人心 2021-02-07 03:05

I have the following ASP.Net MVC Controller method:

public ActionResult DoSomething(DateTime utcDate)
{
   var localTime = utcDate.ToLocalTime();
}
4条回答
  •  梦如初夏
    2021-02-07 04:01

    If you know the DateTime contains a UTC value, you can use the following:

    DateTime iKnowThisIsUtc = whatever;
    DateTime runtimeKnowsThisIsUtc = DateTime.SpecifyKind(
        iKnowThisIsUtc,
        DateTimeKind.Utc);
    DateTime localVersion = runtimeKnowsThisIsUtc.ToLocalTime();
    

    For example, in my current application, I create timestamps in my database with SQL's utcnow, but when I read them into my C# application the Kind proeprty is always Unknown. I created a wrapper function to read the timestamp, deliberately set its Kind to Utc, and then convert it to local time - essentially as above.

    Note that DateTime.ToLocalTime() only doesn't affect the value if one (or both) of the following holds:

    • The DateTime's Kind property is DateTimeKind.Local
    • Your local timezone is such that "no change" is the correct conversion

    I think we can assume the second point isn't true. Thus it seems that iKnowThisIsUtc's Kind property is set to Local already. You need to figure out why whatever is supplying you with these DateTimes thinks they are local.

提交回复
热议问题