C#由当前日期计算相应的周一和周日的实例代码
程序员文章站
2024-02-18 12:31:16
复制代码 代码如下:/// /// 计算本周起始日期(礼拜一的日期) /// &nb...
复制代码 代码如下:
/// <summary>
/// 计算本周起始日期(礼拜一的日期)
/// </summary>
/// <param name="somedate">该周中任意一天</param>
/// <returns>返回礼拜一日期,后面的具体时、分、秒和传入值相等</returns>
public static datetime calculatefirstdateofweek(datetime somedate)
{
int i = somedate.dayofweek - dayofweek.monday;
if (i == -1) i = 6;// i值 > = 0 ,因为枚举原因,sunday排在最前,此时sunday-monday=-1,必须+7=6。
timespan ts = new timespan(i, 0, 0, 0);
return somedate.subtract(ts);
}
/**//// <summary>
/// 计算本周结束日期(礼拜日的日期)
/// </summary>
/// <param name="somedate">该周中任意一天</param>
/// <returns>返回礼拜日日期,后面的具体时、分、秒和传入值相等</returns>
public static datetime calculatelastdateofweek(datetime somedate)
{
int i = somedate.dayofweek - dayofweek.sunday;
if(i != 0) i = 7 - i;// 因为枚举原因,sunday排在最前,相减间隔要被7减。
timespan ts = new timespan(i, 0, 0, 0);
return somedate.add(ts);
}
/**//// <summary>
/// 判断选择的日期是否是本周(根据系统当前时间决定的‘本周'比较而言)
/// </summary>
/// <param name="somedate"></param>
/// <returns></returns>
public static bool isthisweek(datetime somedate)
{
//得到somedate对应的周一
datetime somemon = calculatefirstdateofweek(somedate);
//得到本周一
datetime nowmon = calculatefirstdateofweek(datetime.now);
timespan ts = somemon - nowmon;
if (ts.days < 0)
ts = -ts;//取正
if (ts.days >= 7)
{
return false;
}
else
{
return true;
}
}