How to check whether a given date is DST date or n

2019-06-27 20:14发布

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.

标签: c# dst
3条回答
相关推荐>>
2楼-- · 2019-06-27 20:51

Yes, there is an API: TimeZone.GetDaylightChanges

http://msdn.microsoft.com/en-us/library/system.timezone.getdaylightchanges.aspx

You provide a year and it will return a DaylightTime object, which contains the start and end dates for daylight saving. You can then compare your date against those two to determine if its a DLS date or not.

Whilst this answer has been accepted, please see Matt Johnson's answer below for details why it's not the best answer and why the TimeZoneInfo class should be used instead. https://stackoverflow.com/a/19523173/7122

查看更多
SAY GOODBYE
3楼-- · 2019-06-27 21:05

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.

查看更多
神经病院院长
4楼-- · 2019-06-27 21:08

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.

查看更多
登录 后发表回答