Lookup Date Of Week - CSharp System

CSharp examples for System:DateTime Week

Description

Lookup Date Of Week

Demo Code


using System;//w ww .j  a  v  a 2  s  .  co  m

public class Main{
        public static DateTime LookupDateOfWeek(this DateTime dt, DayOfWeek seekDayOfWeek)
        {
            if (seekDayOfWeek == DayOfWeek.Sunday || seekDayOfWeek > dt.DayOfWeek)
            {
                int diff = seekDayOfWeek - dt.DayOfWeek;
                
                // Fix for sunday == end of the week
                if (diff < 0)
                {
                    diff = 7 + diff;
                }
                var date = dt.AddDays(diff).Date;
                return date;
            }
            else
            {
                int diff = dt.DayOfWeek - seekDayOfWeek;
                return dt.AddDays(-1 * diff).Date;
            }
        }
}

Related Tutorials