Converting UTC DateTime to local DateTime

◇◆丶佛笑我妖孽 提交于 2019-12-09 08:32:48

问题


I have the following ASP.Net MVC Controller method:

public ActionResult DoSomething(DateTime utcDate)
{
   var localTime = utcDate.ToLocalTime();
}

The problem is that localTime will have the exact same value as utcDate. I assume this is because utcDate doesn't know it has a UTC value. So my question is how can I convert utcDate (which I KNOW is UTC) into local?


回答1:


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.




回答2:


as described by MSDN, you need the Kind property of your Date to be UTC, for the ToLocalTime() to work (and convert the date to local time. http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx

Try this:

utcDate = DateTime.SpecifyKind(utcDate, DateTimeKind.Utc);
var localTime = utcDate.ToLocalTime();



回答3:


Try the following:

public static DateTime UtcToPacific(DateTime dateTime)
        {
            return TimeZoneInfo.ConvertTimeFromUtc(dateTime, TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"));
        }

Obviously change Pacific to your local timezone.

If you want to find out what time zones are present on your machine see the following link: http://msdn.microsoft.com/en-us/library/bb397781.aspx




回答4:


or this:

var localTime = new DateTimeOffset(utcDate,TimeSpan.FromHours(0))
                    .ToLocalTime().DateTime;


来源:https://stackoverflow.com/questions/12937968/converting-utc-datetime-to-local-datetime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!