如何传入星期几返回最近的日期
public datetime getdateByWeek(){
DateTime now = DateTime.Now.Date;
string[,] week = new string[,] { "monday",now}, {"tuesday",now.AddDays(1)}, {"wednesday",now.AddDays(2)}, {"thursday",now.AddDays(3)}, {"friday",now.AddDays(4)}, {"saturday",now.AddDays(5)}, {"sunday",now.AddDays(6)} };
return xxx
}
上面这个写法肯定是错的。只是想表达我想要表达的意思,希望传入一个星期几的参数可以返回最近的指定的日期,我自己写了一个烦复了,希望求一个比较简便的方法。
比如
DateTime theDate = getdateByWeek(3);//theDate =2013-07-24 (星期三)
------解决方案--------------------给你个简便方法
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateTime dt = GetDateWeek(3);
Response.Write(dt);
}
}
public DateTime GetDateWeek(int day)
{
DayOfWeek ds = DateTime.Today.DayOfWeek;
int temp = Convert.ToInt32(ds);
int days = temp>=day?temp-day:day-temp;
return DateTime.Now.AddDays(days);
}
------解决方案--------------------private DateTime GetDate(int day)
{
return DateTime.Now.Date.AddDays(day - (int)DateTime.Now.DayOfWeek);