开发者

Calculate weekending for week Saturday to Friday

Given a date I would like to calculate the weekending (Friday) for a week starting from Saturday and ending Friday.

I tried the following开发者_如何学编程 but having problems with February, 02/26/2011 is giving 02/25/2011 onstead of 03/04/2011

System.DateTime weekStart = thedate.AddDays(-Convert.ToInt32(theDate.DayOfWeek) - 1);
System.DateTime weekEnd = weekStart.AddDays(6);
Interaction.MsgBox(weekEnd.ToString());


When you pass in a Saturday, you are subtracting 7 days instead of using that day itself.

DateTime weekStart = theDate.DayOfWeek == DayOfWeek.Saturday
                     ? theDate
                     : theDate.AddDays(-Convert.ToInt32(theDate.DayOfWeek) - 1);

DateTime weekEnd = weekStart.AddDays(6);


That'll do:

System.DateTime weekStart = thedate.AddDays(-(Convert.ToInt32(thedate.DayOfWeek) + 1) % 7);
System.DateTime weekEnd = weekStart.AddDays(6);

Basically, make sure not to subtract more than 6.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜