I am trying to count the number of weekdays (Monday - Friday) by taking the number of days since 01-07-1900 (7th January, 1900), for a given date, and checking the modulus by 7. For modulus values 0 - 5, it's working fine, but for value = 6 (for Saturday), it's not evaluating.

For the given code snippet, for the variable, dayValueInInteger - it evaluates correctly for 0 - 5 but when we compare the variable with value = 6, it is somehow not evaluating.

Please find code snippet and debug attachment.

Date tempDate;
if(monthVar == 1||monthVar == 2){
    tempDate = Date.newInstance(fyEnd.year(), monthVar, i);
    tempDate = Date.newInstance(fyStart.year(), monthVar, i);

// calculating difference here
Integer dayValueInInteger = Math.mod(tempDate.daysBetween(Date.newInstance(1900, 1, 7)), 7);

// checking whether the value is a weekday or not
if(dayValueInInteger != 0 && dayValueInInteger != 6){
    system.debug('---inside if--and value of dayValueInInteger---'+dayValueInInteger);

Debug log screenshot

Can someone please tell me why this is happening?


There is an issue in the code. To notice that, look at the debug which is printing 4 - characters even through you have 3 in your debug at dayValueInInteger*---*.

system.debug('---inside if--and value of dayValueInInteger---'+dayValueInInteger);

The daysBetween is subtracting your date from the past date and the result is negative. Since there is no negative for 0*, the code works.

When the value is 6 (actually it is -6) it enters the if as the condition is satisfied.

Datebetween: Returns the number of days between the Date that called the method and the specified date.

It should be

Date knownSunday = Date.newInstance(1900, 1, 7);
Integer dayValueInInteger = Math.mod(knownSunday.daysBetween(tempDate), 7);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.