Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from UTC to US Mountain time with DST

Tags:

timezone

c#

I have been searching around for how to convert from UTC to mountain time and I have successfully found the following function that everyone says takes into account DST. Whenever it converts from UTC to Mountain it's always -7 for the offset (when it should be -6 currently). Except it doesn't seem to be. Can anyone shine some light on this for me or a way to make it take into account DST?

DateTime utcTime = new DateTime(createdDate.Ticks, DateTimeKind.Utc);
DateTime mountainTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcTime, "US Mountain Standard Time");

Thanks, Dman

like image 336
DMCApps Avatar asked Oct 31 '12 20:10

DMCApps


1 Answers

It looks like there are two zones in .NET (at least on my Windows 8 installation) which are mountain time.

There's "US Mountain Standard Time" which you're using, and which doesn't observe DST (it's for Arizona) - and plain "Mountain Standard Time" which does observe DST. So you just need to get rid of the "US " part and it will work:

using System;

class Test
{
    static void Main()
    {
        DateTime octoberUtc = new DateTime(2012, 10, 1, 0, 0, 0, DateTimeKind.Utc);
        DateTime decemberUtc = new DateTime(2012, 12, 1, 0, 0, 0, DateTimeKind.Utc);
        ConvertToMountainTime(octoberUtc);
        ConvertToMountainTime(decemberUtc);
    }

    static void ConvertToMountainTime(DateTime utc)
    {
        DateTime mountain = TimeZoneInfo.ConvertTimeBySystemTimeZoneId
            (utc, "Mountain Standard Time");

        Console.WriteLine("{0} (UTC) = {1} Mountain time", utc, mountain);
    }
}

Output (UK culture):

01/10/2012 00:00:00 (UTC) = 30/09/2012 18:00:00 Mountain time
01/12/2012 00:00:00 (UTC) = 30/11/2012 17:00:00 Mountain time
like image 159
Jon Skeet Avatar answered Sep 27 '22 19:09

Jon Skeet