[オリジナル]2つの日付が同じ週かどうかを判断する
5776 ワード
カスタマイズをサポートする週の最初の日は何曜日ですか?
コードは簡単で、最後のreturnのビット操作だけが説明する必要があります.
^イソOR:
true^true = false
true^false = true
false^true = true
false^false =false
bool操作では左右に1つだけ成立するとtrueと理解できる.
最後にそれは
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のビット操作だけが説明する必要があります.
^イソOR:
true^true = false
true^false = true
false^true = true
false^false =false
bool操作では左右に1つだけ成立するとtrueと理解できる.
最後にそれは
return (daySpan >= 0) ? fisrtDateOfWeek < secondDateOfWeek : fisrtDateOfWeek >= secondDateOfWeek;