如何获取一周的开始日期时间?
在 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);
共有 0 条评论