I Prefer Jim Developer James Schubert shares his code and his thoughts.

4May/10Off

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)
                .FirstOrDefault();

            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
                     .ConvertTimeFromUtc(dateTime,
                            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 posts:

  1. CopyCat Rails’ Time Extensions
  2. Extending IDataReader
  3. log4net configuration in .NET 3.5

flattr this!

Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.