Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a given date is DST date or not?

Tags:

c#

dst

I have a date as string. There is no time info. For eg. "20131031" ie) 31 oktober 2013.

I want to verify whether it is the date on which DST happens or not ? w.r.t. WesternEurope.

ie) Does c# have an API, to say it is a DST date or not ? I want simply a boolean as return, for the last sunday of October and last sunday of March. which are the dates on which clocks are adjusted.

like image 394
user1872757 Avatar asked Oct 22 '13 09:10

user1872757


2 Answers

Per MSDN Documentation

Important

Whenever possible, use the TimeZoneInfo class instead of the TimeZone class.

You should consider TimeZone deprecated.

Instead, you can check DST for the local time zone like this:

DateTime dt = new DateTime(2013,10,31);
TimeZoneInfo tzi = TimeZoneInfo.Local;
bool isDST = tzi.IsDaylightSavingTime(dt);

For a specific time zone, do this instead:

DateTime dt = new DateTime(2013,10,31);
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
bool isDST = tzi.IsDaylightSavingTime(dt);

If you want to know when the daylight periods start and stop, you'll have to work through the transition rules from tzi.GetAdjustmentRules(). That can get a bit complex though. You would probably be better off using Noda Time for that.

like image 87
Matt Johnson-Pint Avatar answered Nov 08 '22 00:11

Matt Johnson-Pint


You can use the TimeZone.IsDaylightSavingTime method, it takes a DateTime:

public virtual bool IsDaylightSavingTime(
    DateTime time
)

So for example:

var tz = TimeZone.CurrentTimeZone;
var is_dst = tz.IsDaylightSavingTime(DateTime.Now);

See MSDN for more information.

like image 45
Lloyd Avatar answered Nov 07 '22 23:11

Lloyd