How do I determine if a date lies between current week dates?

前端 未结 4 1444
有刺的猬
有刺的猬 2021-01-26 20:49

In C#,

How we are check certain date with in week dates?

Eg: 6/02/2014

Current Weeks: 02/02/2014 - 08/02/2014

so this dates are with in above wee

4条回答
  •  太阳男子
    2021-01-26 20:58

    Here's another solution :)

    public static class DateExtensions
    {
        private static void Swap(ref T one, ref T two)
        {
            var temp = one;
            one = two;
            two = temp;
        }
    
        public static bool IsFromSameWeek(this DateTime first, DateTime second, DayOfWeek firstDayOfWeek = DayOfWeek.Monday)
        {
            // sort dates
            if (first > second)
            {
                Swap(ref first, ref second);
            }
    
            var daysDiff = (second - first).TotalDays;
            if (daysDiff >= 7)
            {
                return false;
            }
    
            const int TotalDaysInWeek = 7;
            var adjustedDayOfWeekFirst = (int)first.DayOfWeek + (first.DayOfWeek < firstDayOfWeek ? TotalDaysInWeek : 0);
            var adjustedDayOfWeekSecond = (int)second.DayOfWeek + (second.DayOfWeek < firstDayOfWeek ? TotalDaysInWeek : 0);
    
            return adjustedDayOfWeekSecond >= adjustedDayOfWeekFirst;
        }
    }
    

    Upd: it appears to have at least twice better performance than @Atiris solution :)

提交回复
热议问题