在 C# 中,只知道当前时间,如何找到一周的开始(包括星期日和星期一)?
类似于:
DateTime.Now.StartWeek(Monday);
使用扩展方法:
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
return dt.AddDays(-1 * diff).Date;
}
}
可以按如下方式使用:
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
标签:DayOfWeek,一周,DateTime,获取,日期,dt,Now,StartOfWeek
From: https://www.cnblogs.com/xiaomandujia/p/17822532.html