Finding a user’s local time from UTC offset

I answered a question over at StackOverflow, and I really liked the answer, so I thought I would share this nifty extension method:

/// <summary>
        /// Convert a given DateTime object to a user's local time, 
        /// taking into account changes in TimeZone rules.
        /// For example, if you were to perform this operation on 
        /// a time now, during EST Daylight Saving, and that time falls 
        /// outside the scope of Daylight Saving time, the rule will adjust accordingly.
        /// </summary>
        /// <param name="dateTime">The DateTime object</param>
        /// <param name="offset">offset from UTC</param>
        /// <returns>User's local time</returns>
        public static DateTime ConvertToLocalDateTime(this DateTime dateTime, int offset)
            TimeZoneInfo destinationTimeZone = TimeZoneInfo.GetSystemTimeZones()
               .Where(x => x.BaseUtcOffset.Hours.Equals(offset)).FirstOrDefault();

            var rule = destinationTimeZone.GetAdjustmentRules().Where(x =>
                x.DateStart <= dateTime && dateTime <= x.DateEnd)

            TimeSpan baseOffset = TimeSpan.Zero;
            if (rule != null)
                baseOffset -= destinationTimeZone.IsDaylightSavingTime(dateTime) ?
                    rule.DaylightDelta : TimeSpan.Zero;

            DateTimeOffset dto = DateTimeOffset.Parse(dateTime.ToString());
            return new DateTime(TimeZoneInfo
                            destinationTimeZone).Ticks + baseOffset.Ticks);

The summary basically says it all. I ran through a couple of tests with this, I’d like to know if anyone uses this and makes modifications to it!

Related Articles