如何在 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);