SidD
SidD

Reputation: 6377

Incorrect UTC Datetime Calculated based on TimeZoneInfo

I have a timezoneinfo Central Europe Standard Time, which is showing UTC +01:00, when i execute the code it shows 2 hrs before time instead of 1 hr. Below is the sample code

static void Main(string[] args)
    {
        var strTimeZoneInfo = "Central Europe Standard Time";
        var datetimeDST = Convert.ToDateTime("2019-07-18 18:17:00");
        var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(strTimeZoneInfo);
        var dtUTC= TimeZoneInfo.ConvertTimeToUtc(datetimeDST, timeZoneInfo);
        Console.WriteLine(Convert.ToString(dtUTC));
        Console.ReadKey();
    }

So instead of 2019-07-18 17:17:00 i am getting 2019-07-18 16:17:00. Can someone explain how to resolve this without using Noda or other external library.

Referred Below links but not clear how to resolve this problem.

Also referred this link's answer but it's not working.

Upvotes: 0

Views: 133

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156708

Even though "Central Europe Standard Time" is the Id property for that TimeZoneInfo, but it actually handles both Standard and Daylight time within that time zone depending on the date you're talking about. I understand it is confusing because that TimeZoneInfo includes "UTC+01:00" in the Display Name, even though it's currently in Daylight Savings Time.

But in this case, the date you're giving it is during a Daylight Savings Time period, so the offset should be +02:00, not +01:00. The library is producing the correct results.

var strTimeZoneInfo = "Central Europe Standard Time";
var datetimeDST = Convert.ToDateTime("2019-07-18 18:17:00");
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(strTimeZoneInfo);
Console.WriteLine(timeZoneInfo.DisplayName);
Console.WriteLine(timeZoneInfo.StandardName);
Console.WriteLine(timeZoneInfo.DaylightName);
Console.WriteLine(timeZoneInfo.IsDaylightSavingTime(datetimeDST));
Console.WriteLine(timeZoneInfo.GetUtcOffset(datetimeDST));
var dtUTC = TimeZoneInfo.ConvertTimeToUtc(datetimeDST, timeZoneInfo);
Console.WriteLine(dtUTC.ToString(CultureInfo.InvariantCulture));

Output:

(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague
Central Europe Standard Time
Central Europe Daylight Time
True
02:00:00
07/18/2019 16:17:00

Upvotes: 3

Related Questions