我如何只知道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);