开发者

Calculating holidays

A number of holidays move around from year to year. For example, in Canada Victoria day (aka the May two-four weekend) is the Monday before May 25th, or Thanksgiving is the 2nd Monday of October (in Canada).

I've been using variations on this Linq query to get the date of a holiday for a given year:

var year = 2011;
var month = 10;
var d开发者_C百科ow = DayOfWeek.Monday;
var instance = 2;

var day = (from d in Enumerable.Range(1,DateTime.DaysInMonth(year,month))
let sample = new DateTime(year,month,d)
where sample.DayOfWeek == dow
select sample).Skip(instance-1).Take(1);

While this works, and is easy enough to understand, I can imagine there is a more elegant way of making this calculation versus this brute force approach.

Of course this doesn't touch on holidays such as Easter and the many other lunar based dates.


And it gets complicated if you have to consider non-christian holidays. For example, jewish holidays are based on the jewish calender..

Maybe not so elegant, but more error prone - you can just add a table of all relevant holidays for the next 100 years.


int margin = (int)dow - (int)new DateTime(year, month, 1).DayOfWeek;
if (margin < 0) margin = 7 + margin; 
int dayOfMonth = margin + 7*(instance - 1) //this is for 0-based day number, add 1 if you need 1-based. instance is considered to be 1-based

Please note that I wrote it without trying to compile, so it is to give the idea, but may require some clean up. Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜