Compute a number of days (or/and Sundays)

In a ListBox based window, I have two dates (Start and End).

I noticed that my way to compute the number of ellapsed days (without Sundays) or ellapsed Sundays (only Sundays) gives wrong results.

The dates are stored as ISO (Date only, no Time part used).

How do you compute that ?

Quick and dirty (one of my talents): :wink:

Public Function AddIntervalWorkingdays(Extends d As DateTime, Days As Integer) As DateTime
  While Days > 0
    d = d.AddInterval(0,0,1)
    If d.DayOfWeek <> 1 And d.DayOfWeek <> 7 Then
      Days = Days - 1
    End If
  Return d
End Function

Thank you Sasha.

I will check that asap.

1 Like

Sorry, I didn’t read your question carefully enough. Please try the following method. (I couldn’t test it, but it should work)

Public Function CountDaysWithOrWithoutSundays(startDate As DateTime, endDate As DateTime, Optional CountOnlySundays As Boolean = False) As Integer
  // Check is startDate is before endDate
  If startDate > endDate Then
    Return 0 // or report an error, if startDate is later than endDate
  End If
  Dim countedDays As Integer = 0
  Dim currentDate As DateTime = startDate
  While currentDate <= endDate
    // check if current day is no sunday (weekday 1 in Xojo)
    If CountOnlySundays Then
      If currentDate.DayOfWeek = 1 Then
        countedDays = countedDays + 1
      End If
      If currentDate.DayOfWeek <> 1 Then
        countedDays = countedDays + 1
      End If
    End If
    // Gehe zum nächsten Tag
    currentDate = currentDate.AddInterval(0,0,1)
  Return countedDays
End Function

In my opinion, you’re the best way to get through the days. Working with divisors and fractions just makes things unnecessarily more complex.

I checked my code and I count Day = Day + 1.
But this gaves me 2 Sundays when Start and End Sundays are the same date.

I forgot if there was other errors in my results.

It tooks me years to realize there is a bug because the case happens only once here and then (just like leap year).

Leap year:
I have a bug there and never noticed it until someone birthdate was entered and that person was born on February 29th.
And that happened only on my test list of persons (French politics I found on the internet).
The software is in use since early 2013 and no one reported any error to me (that does not means no one knows…).

Happy Macintosh 40th birthday !