我使用以下方法获取下周一周一和周五的日期。
例如,今天是1/6/2017。如果我运行它,我希望得到以下结果:
monday = 1/9/2017 friday = 1/13/2017
如果我在本周早些时候运行该方法,该方法可以正常运行,但如果我在星期五或星期六之后运行它,它将从现在开始(不是下周)返回星期一和星期五的日期。
例如,今天(6日星期五)运行它,我得到以下结果:
monday = 1/16/2017 friday = 1/20/2017
以下是方法:
public static DateTime NextWeekRange(DateTime start, DayOfWeek day)
{
var add_days = ((int)day - (int)start.DayOfWeek + 7) % 7;
return start.AddDays(add_days);
}
我称之为:
var monday = NextWeekRange(DateTime.Today.AddDays(i_today), DayOfWeek.Monday);
var friday = NextWeekRange(DateTime.Today.AddDays(i_today + 4), DayOfWeek.Friday);
我不太确定我的错误,所以另一双眼睛会有所帮助!
谢谢!
答案 0 :(得分:0)
DateTime MyDate = DateTime.Now;
DateTime NextMondayDate;
DateTime NextFridayDate;
Boolean Test = true;
while (Test)
{
if (MyDate.DayOfWeek.ToString().ToUpper() == "MONDAY")
{
NextMondayDate = MyDate;
NextFridayDate = MyDate.AddDays(4);
Test = false;
}
else if (MyDate.DayOfWeek.ToString().ToUpper() == "FRIDAY")
{
NextFridayDate = MyDate;
NextMondayDate = MyDate.AddDays(3);
Test = false;
}
else
{
MyDate = MyDate.AddDays(1);
}
}