Tadhg
Tadhg

Reputation: 193

Converting time from different timezone with daylight savings included

I have process that accepts datetime value with timezone as a string (data comes from outside system). I need to translate this datetime to what the time would have been at the local machines timezone.

Example code:

string cetId = "Central European Standard Time";
if (timeZone == "CET")
{
    TimeZoneInfo cetZone = TimeZoneInfo.FindSystemTimeZoneById(cetId);
    returnDateTime = TimeZoneInfo.ConvertTime(statusDateTime, cetZone, TimeZoneInfo.Local);
}
else if (timeZone == "CEST")
{
    TimeZoneInfo cestZone = TimeZoneInfo.FindSystemTimeZoneById(cetId);
    returnDateTime = TimeZoneInfo.ConvertTime(statusDateTime, cestZone, TimeZoneInfo.Local);
}

Do I need to do anything specific if the time is CEST (central european summer time) instead of CET (central european time) or does .net TimeZoneInfo object handle that scenario?

Upvotes: 6

Views: 5772

Answers (3)

Chris Moschini
Chris Moschini

Reputation: 37967

I created a library a while back to encapsulate these kinds of transforms:

https://github.com/b9chris/TimeZoneInfoLib.Net/blob/master/TimeZoneInfoLib/TimeZone/UtcTimeZone.cs

Might be useful to you, or you may just want to pick it over to double-check your code. One of the things it encapsulates is @Brian's caveat - so it has explicit method names relating to the .Kind property, that throw useful exceptions if the .Kind is wrong. It also takes a little bit of the grunt work out of getting useful/common/daylight time names and abbreviations:

https://github.com/b9chris/TimeZoneInfoLib.Net/blob/master/TimeZoneInfoLib/TimeZone/TimeZoneShortNameMap.cs

Upvotes: 0

Brian
Brian

Reputation: 1397

From TimeZoneInfo.ConvertTime()

The value of the Kind property of the dateTime parameter must correspond to the sourceTimeZone parameter, as the following table shows.

Just want to add that you need to watch out for the 'Kind' property of your StatusDateTime. In your case, it HAS to be 'Unspecified'. Check out the 'Remarks' section

Upvotes: 0

You should be fine.

You are telling ConvertTime what both time zones (source and target) are.

Do you have a specific problem with this or are you just asking for confirmation?

Upvotes: 1

Related Questions