C# 获取本周第一天(以星期一为第一天)
using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("本周第一天:{0}", GetWeekFirstDate(DateTime.Now));
Console.Read();
}
/// <summary>
/// 获取本周第一天(以星期一为第一天)
/// </summary>
/// <param name="dateTime">当前时间 DateTime.Now or DateTime.UtcNow</param>
/// <returns>后面的具体时、分、秒和传入值相等</returns>
public static DateTime GetWeekFirstDate(DateTime dateTime)
{
int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
// 因为是以星期一为第一天,所以要判断weeknow等于0时,要向前推6天。
weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
int daydiff = (-1) * weeknow;
// 本周第一天
return Convert.ToDateTime(dateTime.AddDays(daydiff));
}
}
}