C#/.NET/.NET Core应用程序编程开发中如何获取指定日期所在周的第一天?
2.81K 次浏览
3 个回答
-
创建一个日期的扩展方法,如下:
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);
-
使用Fluent DateTime第三方类库,示例如下:
var monday = DateTime.Now.Previous(DayOfWeek.Monday); var sunday = DateTime.Now.Previous(DayOfWeek.Sunday);