Monday, September 26, 2011

Convert from UTC Time to Local Time with C#

It's that time of the year again. Yes, it's time for my annual blog post. This one is just a blurb about converting from UTC to Local time on Windows. It's not straightforward so you might find this helpful.

public DateTime GetLocalTimeFromUTC(long theUTCTime = 1314163440)
 // Using parameter assignment I set theUTCTime to my birthday.
 // Notice: this UTC is in seconds, it's not from Windows

 // if UTC time is from Windows then you don't need this. .NET returns UTC in milliseconds.
 // If your UTC time comes from elsewhere you'll probably need to multiply by 1000 to get milliseconds theUTCTime *= 1000;

 // make a DateTime for the start of the UTC Epoch
 var aEpochStart = new DateTime(1970, 1, 1);

 // calculate a timespan utilizing windows-specific "ticks"
 var aTimeSpan = new TimeSpan(TimeSpan.TicksPerMillisecond * theUTCTime);

 // add the timespan to the start of the Epoch and you get your local time
 var aLocalTime = aEpochStart.Add(aTimeSpan);
 return aLocalTime;