Is there a way to get daylight savings time info for non local timezones

47 Views Asked by At

I would like to find the equivalent daylight savings time zone for a given standard time zone. Here's a code snippet:

protected DateTime ConvertTimeZoneFromUTC(DateTime dateTime) {
    //dateTime is utc
    var dateUtc = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
    var currentTimeZone = "";

    //The user's timezone name is stored in WindowsTimeZoneName e.g. "US Mountain Standard Time"
    var convertTimeZoneFromUTC =  TimeZoneInfo.ConvertTimeFromUtc(dateUtc, TimeZoneInfo.FindSystemTimeZoneById(WindowsTimeZoneName));
    if (TimeZoneInfo.Local.IsDaylightSavingTime(convertTimeZoneFromUTC))
    {
        //Is there a way to get IsDaylightSavingTime for the non local timezone?
        //For me TimeZoneInfo.Local is "Eastern Daylight Time"
        currentTimeZone = TimeZoneInfo.Local.DaylightName; //I would like to get "US Mountain Daylight Time" for the user's timezone
    }

    convertTimeZoneFromUTC = TimeZoneInfo.ConvertTimeFromUtc(dateUtc, TimeZoneInfo.FindSystemTimeZoneById(currentTimeZone)); //Would like to convert to "US Mountain Daylight Time"
}
1

There are 1 best solutions below

0
Eric On

The reason

 var convertTimeZoneFromUTC =  TimeZoneInfo.ConvertTimeFromUtc(dateUtc, TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time"));

doesn't adjust for daylight savings time is that "US Mountain Standard Time" is only for Arizona, which doesn't use daylight savings time. In my case, I was testing with Colorado. In order to get compensate for daylight savings time I need to specify "Mountain Standard Time" instead.

In order to determine if a specified time zone is in daylight savings time, you need to instantiate an instance of the TimeZoneInfo using FindSystemTimeZoneById and then you test if a given time is in DST like so:

    var dateUtc = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
    var currentTimeZone = "";

    TimeZoneInfo localZone = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time");
    DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(dateUtc, localZone);


    if (localZone.IsDaylightSavingTime(localTime))
    {
        Console.WriteLine(localTime.ToString() + " is in daylight savings time.");
    }
    else
    {
        Console.WriteLine(localTime.ToString() + " is NOT in daylight savings time.");
    }