Friday, March 21, 2008

Converting to a different timezone using C#

Here is some code that I like to use for converting between timezone using C#. There are two methods. One that uses DateTime and the other uses DateTime? which can be null.
/// <summary> /// Converts a date that is assumed to be have an offset from UTC of sourceUtcOffset to an offset from UTC of targetUtcOffset /// </summary> /// <param name="sourceDate">The date and time that needs to be converted</param> /// <param name="sourceUtcOffset">The offset from UTC of the sourceDate</param> /// <param name="targetUtcOffset">The offset from UTC of the timezone that the DateTime should be converted to.</param> /// <returns>A DateTime that has been adjusted to the offset from UTC of targetUtcOffset</returns> public static DateTime ConvertDateTime2AnotherTimezone(DateTime sourceDate, int sourceUtcOffset, int targetUtcOffset) { DateTime asUtcDateTime = sourceDate.AddHours(sourceUtcOffset); DateTime targetDateTime = asUtcDateTime.AddHours(targetUtcOffset); return targetDateTime; }
/// <summary> /// Converts a date that is assumed to be have an offset from UTC of sourceUtcOffset to an offset from UTC of targetUtcOffset /// </summary> /// <param name="sourceDate">The date and time that needs to be converted</param> /// <param name="sourceUtcOffset">The offset from UTC of the sourceDate</param> /// <param name="targetUtcOffset">The offset from UTC of the timezone that the DateTime should be converted to.</param> /// <returns>A DateTime that has been adjusted to the offset from UTC of targetUtcOffset</returns> public static DateTime? ConvertDateTime2AnotherTimezone(DateTime? sourceDate, int sourceUtcOffset, int targetUtcOffset) { if (sourceDate.HasValue) { DateTime nonNullSourceDate = sourceDate.Value; DateTime asUtcDateTime = nonNullSourceDate.AddHours(-1 * sourceUtcOffset); DateTime targetDateTime = asUtcDateTime.AddHours(targetUtcOffset); return new DateTime?(targetDateTime); } // if there is no value, then it is null, and thus we have nothing to convert else { return sourceDate; } }

No comments: