Is there a generic TimeZoneInfo For Central Europe?
Asked Answered
P

3

21

Is there a generic TimeZoneInfo for Central Europe that takes into consideration both CET and CEST into one?

I have an app that is doing the following:

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); 
DateTimeOffset dto = new DateTimeOffset(someDate, tzi.BaseUtcOffset);
var utcDate = dto.ToUniversalTime().DateTime;

The problem is that this is returning the wrong utcDate because the BaseUtcOffset is +1 instead of +2. It appears that CET has DST as well and depending on the time of the year it is +1 or +2.

Procreate answered 4/4, 2012 at 21:8 Comment(0)
H
14

Firstly, I'd like to applaud mgnoonan's answer of using Noda Time :) But if you're feeling less adventurous...

You're already using the right time zone - but you shouldn't be using BaseUtcOffset which is documented not to be about DST:

Gets the time difference between the current time zone's standard time and Coordinated Universal Time (UTC).

It can't possibly take DST into consideration when you're not providing it a DateTime to fetch the offset for :)

Assuming someDate is a DateTime, you could use:

DateTimeOffset dto = new DateTimeOffset(someDate, tzi.GetUtcOffset(someDate));

Or just ConvertTimeToUtc:

var utcDate = TimeZoneInfo.ConvertTimeToUtc(someDate, tzi);

Note that you should work out what you want to do if your local time occurs twice due to a DST transition, or doesn't occur at all.

Hunter answered 4/4, 2012 at 21:21 Comment(4)
I knew I should have just waited for you to answer. ;)Fold
Great explanation. Although Noda Time might be the right tool, this worked and is the best solution for the current project.Procreate
Just a minor comment: ConvertTimeToUtc is now a static method so you need to call var utcDate = TimeZoneInfo.ConvertTimeToUtc(someDate, tzi)Gabar
@Eoin: How odd - I wonder how I got that wrong. Will fix. (There are a bunch of static methods in TimeZoneInfo taking a TimeZoneInfo as a parameter. I've never understood why...)Hunter
F
5

Maybe Noda Time can help you out?

Fold answered 4/4, 2012 at 21:11 Comment(1)
Will definitely take Noda Time into consideration next time I use dates. Thanks!Procreate
H
2

Using .Net Core referance ConvertTimeToUtc(DateTime, TimeZoneInfo)

        // Get Current Central European Standard Time
        DateTime thisTime = DateTime.Now;
        TimeZoneInfo cet = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
        DateTime cetTime = TimeZoneInfo.ConvertTime(thisTime, TimeZoneInfo.Local, cet);
        Console.WriteLine("Time in {0} zone: {1}", cet.IsDaylightSavingTime(cetTime) ? cet.DaylightName : cet.StandardName, cetTime);

        // Output:
        // Time in Central European Standard Time zone: 08-03-2024 05:26:03
Hyperemia answered 8/3 at 4:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.