支持自定义每周的第一天是星期几
1 public static class DateTimeExtension 2 { 3 public const DayOfWeek TheFirstDayOfWeek = DayOfWeek.Monday; 4 5 private static int GetDayOfWeek(this DateTime date, DayOfWeek theFirstDayOfWeek = TheFirstDayOfWeek) 6 { 7 return ((int) date.DayOfWeek - (int) theFirstDayOfWeek + 7) % 7; 8 } 9 10 public static bool IsInSameWeek(this DateTime firstDate, DateTime secondDate, 11 DayOfWeek theFirstDayOfWeek = TheFirstDayOfWeek) 12 { 13 var daySpan = (secondDate.Date - firstDate.Date).TotalDays; 14 if (daySpan >= 7d || daySpan <= -7d) 15 { 16 return false; 17 } 18 19 var fisrtDayOfWeek = firstDate.GetDayOfWeek(theFirstDayOfWeek); 20 var secondDayOfWeek = secondDate.GetDayOfWeek(theFirstDayOfWeek); 21 22 return (daySpan >= 0) ^ (fisrtDayOfWeek >= secondDayOfWeek); 23 } 24 25 public static bool IsLastWeek(this DateTime date, DayOfWeek theFirstDayOfWeek = TheFirstDayOfWeek) 26 { 27 return date.AddDays(7).IsInSameWeek(DateTime.Today, theFirstDayOfWeek); 28 } 29 30 public static bool IsThisWeek(this DateTime date, DayOfWeek theFirstDayOfWeek = TheFirstDayOfWeek) 31 { 32 return date.IsInSameWeek(DateTime.Today, theFirstDayOfWeek); 33 } 34 }
代码很简单,只有最后一个return的位操作可能需要解释下
^ 异或:
true^true = false
true^false = true
false^true = true
false^false =false
用在bool操作可以理解为左右两边只有一个成立则为true
最后那个相当于
return (daySpan >= 0) ? fisrtDateOfWeek < secondDateOfWeek : fisrtDateOfWeek >= secondDateOfWeek;