Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate the number of days, minus Sundays, between two dates in C#?

Tags:

c#

I am creating a Library Management System.

I have used the timestamp to calculate the Date Difference and with the help of date difference I am calculating the Fine also.

Now this date difference includes all days in a week. But for a library application fine should be charged only for 6 days(Mon - Sat) in Week.

I am not able to do this.

Can anyone help me out in performing this task?

Thanks in advance!!

like image 914
sheetal Avatar asked Jul 07 '09 17:07

sheetal


2 Answers

Essentially, you can calculate the raw number of days; you need to find the number of Sundays to be subtracted from that number. You know that every 7 days is a Sunday, so you can divide your raw number of days by 7, and subtract that number from your raw number of days. Now you need to remove the number of Sundays in the remainder of the week that exists; a mod of the raw number of days will tell you the remainder days. To find out if that span includes a Sunday, you must know the day of the week of the first day; if you define Monday to be 0, Tuesday to be 1, Wednesday to be 3, etc., then if you add the value of the day of the week of the beginning of the span to the mod (7) of the raw number of days, if the number is 6 or greater, you have spanned an additional Sunday, and should remove 1 day from your fine number.

In pseudocode:

int fine;
int numdays =  endDay - startDay;

fine = numdays - (numdays / 7);

int dayOfWeek = startDate.DayOfWeek;
if (dayOfWeek + (numdays % 7) > 6)
{
   fine = fine - 1;
}
like image 60
Paul Sonier Avatar answered Jan 02 '23 01:01

Paul Sonier


This will do it:

private int DaysLate(DateTime dueDate, DateTime returnDate)
{
    var ts = returnDate - dueDate;
    int dayCount = 0;

    for (int i = 1; i <= ts.Days; i++)
    {
        if (dueDate.AddDays(i).DayOfWeek != DayOfWeek.Sunday)
            dayCount++;
    }

    return dayCount;
}
like image 28
raven Avatar answered Jan 02 '23 01:01

raven