Page 1 of 1

Calculate number of working days between two dates

Posted: 27 Jun 2011
by JoshM
I couldn't find a function which calculates the number of working days between two dates, so I created one. Perhaps this modest function can save someone some time.

Function code

Code: Select all

{ 27-6-2011: NumOfWorkDays - Function for calculating the number of days between two dates }

Inputs:
StartDate(NumericSimple),
EndDate(NumericSimple);

Vars:
numOfDaysCounter(0), // Number of working days between dates
julStartDate(0), // Start date converted to Julian date
julEndDate(0) // End date converted to Julian
;

julStartDate = DateToJulian(StartDate); // Convert dates to Julian format
julEndDate = DateToJulian(EndDate);

If julEndDate > julStartDate then begin // End date should be higher then starting date
For value1 = julEndDate DownTo julStartDate + 1 begin
value2 = JulianToDate(value1); // Convert julian date back to normal date
value3 = DayOfWeek(value2); // Determine day of week
if value3 > 0 and value3 < 6 then // Day should be higher then 0 (Sunday) and lower then 6 (Saturday)
numOfDaysCounter = numOfDaysCounter + 1;
end;
end;

NumOfWorkDays = numOfDaysCounter;
Usage examples
For example, the days between the first trade and last trade:

Code: Select all

if LastBarOnChart_s then begin
Print("EntryDate: ", EntryDate(totaltrades), " ExitDate: ", Exitdate(1));
Print("Number of working days: ", NumOfWorkDays(entrydate(totalTrades), exitdate(1)));
end;
Or the number of days between the current bar and the bar 300 bars ago:

Code: Select all

Print("Number of working days: ", NumOfWorkDays(date[300], date));
Or the number of days between today and Monday a week ago:

Code: Select all

value87 = 1110620.00;
value88 = 1110627.00;
Print("Number of working days: ", NumOfWorkDays(value87, value88));
Regards,
Josh