ASP.NET - How to exclude fridays and saturdays in a month

Asked By dinesh on 12-Feb-12 11:38 PM
Hi friends,

         in my asp.net application in one of my functionalities i need to exclude fridays and saturdays in a month. When i select the start date irrespective of the month the end date should be 30th day from that starting day and i need to remove the number of fridays and saturdays in between these start date and end date. Please suggest me how to go on with this.

Thanks and Regards,
Dinesh
Web Star replied to dinesh on 12-Feb-12 11:55 PM
you can get number of days without including Fridays and Saturdays in sql server query as follows

SET DATEFIRST 7
DECLARE @Date datetime
DECLARE @MonthDate datetime
SET @Date='1 Apr 2008'
SET @MonthDate=DATEADD(mm,DATEDIFF(mm,0,@Date),0)
print @MonthDate
SELECT COUNT(DateVal) FROM
(
SELECT DATEADD(dd,v.number,@MonthDate) AS DateVal
FROM master..spt_values v
WHERE v.type='p'
AND DATEADD(dd,v.number,@MonthDate)<=DATEADD(mm,1,@MonthDate)


AND DATEPART(dw,DATEADD(dd,v.number,@MonthDate)) NOT IN (6,7)
)t

Chintan Vaghela replied to dinesh on 13-Feb-12 12:06 AM

Hello,

 

Below given method find out, that current day is Saturday or Friday i.e find out the WeekEnd.

  public static bool IsWeekEnd(DateTime dateTime)

    {

 

      bool isWeekEnd = false;

 

      switch (dateTime.DayOfWeek)

      {

 

        case DayOfWeek.Friday:

 

        case DayOfWeek.Saturday:

 

          isWeekEnd = true;

 

          break;

 

      }

 

      return isWeekEnd;

 

    }

 

This method returns true if the current date is Satuarday or Firday otherwise return false.

 

 

 

    public static DateTime FindBusinessDate(int numberOfBusinessDays, DateTime fromDate)

    {

 

 

      int businessDays = 0;

 

      int noOfDays = numberOfBusinessDays;

 

      for (int i = 1; i <= numberOfBusinessDays; i++)

      {

 

        if (!IsWeekEnd(fromDate))

 

          businessDays++;

 

 

        //When businessDays is not equal to noOfDays,

 

        //add one day in the current date.

 

        if (businessDays != noOfDays)

        {

 

          fromDate = fromDate.AddDays(1);

 

        }

 

        else

        {

 

          break;

 

        }

 

      }

 

      return fromDate;

 

    }

 

We can use above method as follows:
Response.Write(FindBusinessDate(30, Convert.ToDateTime("2 / 13 / 2012")));

 

 

Hope this is helpful !

Thanks

 

 

 

 

 

Sandeep Mittal replied to dinesh on 13-Feb-12 12:25 AM
DECLARE @StartDate DATETIME, @EndDate DATETIME
SET @StartDate='13 Feb 2012'
SET @EndDate= dateADD(d, 29, @StartDate)
 
;WITH dates AS(
  SELECT @StartDate AS dt
  UNION ALL
  SELECT DATEADD(d, 1, dt) FROM dates WHERE dt < @EndDate
)
 
SELECT  count(1)
FROM    dates
WHERE   DATEPART(dw,dt) NOT IN (6,7)