B4J Code Snippet Adding working days to date

Adding working days to date

Sometimes you do not just want to add a certain number of days to a date but you have to take the working days into account.
For example: Two business days to delivery or five business days when the customer needs an answer.

The following AddWorkingDays function does this.
It is possible to calculate +5 or -3 days.

This is just a very easy way to calculate working days
No holidays are considered.
(translate by google)

B4X:
Sub AddWorkingDays( DateTicks As Long, NumberOfDays As Int) As Long
    Dim Result As Long = DateTicks
    
    Do Until NumberOfDays = 0
        Result = DateTime.Add( Result, 0, 0, Sgn( NumberOfDays))
        Select Case DateTime.GetDayOfWeek( Result)
            Case 1,7
                'Weekend do nothing
            Case Else
                NumberOfDays = NumberOfDays - Sgn(NumberOfDays)
        End Select
    Loop
    Return Result
End Sub

'The Sgn function returns the value of a sign of a number.
'Return Values -1,0,1
Sub Sgn( Number As Long)  As Int
    Select True
        Case Number > 0
            Return 1
        Case Number < 0
            Return -1
        Case Else
            Return 0
    End Select
End Sub
B4X:
Dim Now As Long =  DateTime.Now    '2018-10-27
Log( DateTime.Date( AddWorkingDays( Now, -6)))   '2018-10-19
Log( DateTime.Date( AddWorkingDays( Now, 3)))    '2018-10-31
Log( DateTime.Date( AddWorkingDays( Now, 6)))    '2018-11-05
 
Top