Tuesday, January 25, 2011

Time Zones Pacific UTC

Convert from Pacific Time to UTC/GMT

private DateTime ToUtc(DateTime pacificDateTime)
{
TimeZoneInfo pacificZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
// "Pacific Standard Time" it's the ID regardless of daylight saving time (i.e. no matters if right now is daylight saving time, the ID name remains the same)

DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(pacificDateTime, pacificZone);
// it automatically takes care of daylight saving time

return utcTime;
}

Convert from UTC/GMT to Mountain Time

private DateTime ToMountain(DateTime utcDate)
{
TimeZoneInfo mountainZone = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time");
// "Mountain Standard Time" it's the ID regardless of daylight saving time (i.e. no matters if right now is daylight saving time, the ID name remains the same)

DateTime mountainTime = TimeZoneInfo.ConvertTimeFromUtc(utcDate, mountainZone);
// it automatically takes care of daylight saving time

return mountainTime;
}

Time zone converter

private DateTime ToMountain(DateTime datetime, string originalTimeZoneID)
{
// The strings requested by the method are the ID regardless of daylight saving time (i.e. no matter if right now is daylight saving time, the ID name remains the same)
return TimeZoneInfo.ConvertTimeBySystemTimeZoneId(datetime, originalTimeZoneID, "Mountain Standard Time");
}

1 comment:

fc said...

Generic methods

public const string MOUNTAIN_TIMEZONE_ID = "Mountain Standard Time";
public const string PACIFIC_TIMEZONE_ID = "Pacific Standard Time";

public static DateTime ToUtc(DateTime sourceDateTime, string sourceTimezoneID) {
TimeZoneInfo originalTimeZone = TimeZoneInfo.FindSystemTimeZoneById(sourceTimezoneID);
return TimeZoneInfo.ConvertTimeToUtc(sourceDateTime, originalTimeZone);
}

public static DateTime FromUtc(DateTime utcDateTime, string destinationTimezoneID) {
TimeZoneInfo originalTimeZone = TimeZoneInfo.FindSystemTimeZoneById(destinationTimezoneID);
return TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, originalTimeZone);
}