Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting UTC DateTime to local DateTime

Tags:

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?

like image 950
Shane Courtrille Avatar asked Oct 17 '12 15:10

Shane Courtrille


People also ask

How do you convert UTC to local time?

Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.).

How do you convert UTC to local time zone in Python?

This datetime object will have no timezone associated with it. Therefore assign the UTC timezone to this datetime object using replace(tzinfo=pytz. UTC) function. Convert the timezone of the datetime object to local timezone by calling the astimezone() function on datetime object.

How do I convert datetime to local time?

To convert the time in any designated time zone to local time, use the TimeZoneInfo. ConvertTime method. The value returned by the conversion is a DateTime whose Kind property always returns Local. Consequently, a valid result is returned even if ToLocalTime is applied repeatedly to the same DateTime.

How do I convert UTC to local date in Excel?

=TIMEVALUE(RIGHT(A1,5))+DATEVALUE(SUBSTITUTE(LEFT(A1,10),".","/"))+TIME(8,0,0) in B1. r-click cell > format > custom : yyyy. mm. dd hh:mm.


1 Answers

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.

like image 193
Rawling Avatar answered Sep 28 '22 11:09

Rawling