I wrote two extension methods to convert times from local time to UTC and back. This is what I have:
public static DateTime ConvertUserTimeToUTCTime(this DateTime TheUserTime, string TheTimezoneID)
{
TheUserTime = new DateTime(TheUserTime.Year, TheUserTime.Month,
TheUserTime.Day, TheUserTime.Hour, TheUserTime.Minute,
TheUserTime.Second, DateTimeKind.Local);
TimeZoneInfo TheTZ = TimeZoneInfo.FindSystemTimeZoneById(TheTimezoneID);
TimeSpan TheOffset = TheTZ.GetUtcOffset(TheUserTime);
DateTimeOffset TheUTCTimeOffset = new DateTimeOffset(
TheUserTime, TheOffset).ToUniversalTime();
DateTime TheUTCTime = new DateTime(TheUTCTimeOffset.Year,
TheUTCTimeOffset.Month, TheUTCTimeOffset.Day, TheUTCTimeOffset.Hour,
TheUTCTimeOffset.Minute, 0, DateTimeKind.Utc);
return TheUTCTime;
}
public static DateTime ConvertUTCTimeToUserTime(this DateTime TheUTCTime,
string TheTimezoneID)
{
TimeZoneInfo TheTZ = TimeZoneInfo.FindSystemTimeZoneById(TheTimezoneID);
DateTime UTCTime = new DateTime(TheUTCTime.Year, TheUTCTime.Month,
TheUTCTime.Day, TheUTCTime.Hour, TheUTCTime.Minute, 0, DateTimeKind.Utc);
DateTime TheUserTime = TimeZoneInfo.ConvertTime(UTCTime, TheTZ);
return TheUserTime;
}
I use these two quite frequently in my app and I was wondering if they're thread safe. Also, would there be any benefit to putting these two method in an abstract class and then having all the classes that involve time operations inherit from this abstract class?
Thanks for your suggestions on this time conversion topic.