Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
ShowAll Questionssorted byDate Posted
priyaforsfdc

# Calculate how many working and how many weekends in between Start date and End date in apex?

Calculate how many working and how many weekends in between Start date and End date.

Surprise

Hi ,

Below given code should help u in calculating number of working days.Just to let u know it is not my code.

private Integer getDiffBusinessDays(Date startdt, Date enddt) {
Date tempdate = null;
if (startdt > enddt) {
tempdate = enddt;
enddt = startdt;
startdt = tempdate;
}
Integer i = Math.mod((date.newinstance(1985, 6, 24)).daysBetween(startdt),7); // 24/6/85 was a monday
Map<Integer, Map<Integer, Integer>> m = new Map<Integer, Map<Integer, Integer>> {
0 => new Map<Integer, Integer> { 1 => 2 , 2 => 3 , 3 => 4 , 4 => 5 , 5 => 5 , 6 => 5 },
1 => new Map<Integer, Integer> { 1 => 2 , 2 => 3 , 3 => 4 , 4 => 4 , 5 => 4 , 6 => 5 },
2 => new Map<Integer, Integer> { 1 => 2 , 2 => 3 , 3 => 3 , 4 => 3 , 5 => 4 , 6 => 5 },
3 => new Map<Integer, Integer> { 1 => 2 , 2 => 2 , 3 => 2 , 4 => 3 , 5 => 4 , 6 => 5 },
4 => new Map<Integer, Integer> { 1 => 1 , 2 => 1 , 3 => 2 , 4 => 3 , 5 => 4 , 6 => 5 },
5 => new Map<Integer, Integer> { 1 => 0 , 2 => 1 , 3 => 2 , 4 => 3 , 5 => 4 , 6 => 5 },
6 => new Map<Integer, Integer> { 1 => 1 , 2 => 2 , 3 => 3 , 4 => 4 , 5 => 5 , 6 => 5 }
};
Integer i2 = Math.mod((startdt.daysBetween(enddt)),7);
Integer i3 = (m.get(i)).get(i2);
if (i2 == null || i2 < 1 || i2 > 6) {
if (i >= 0 && i <= 4) { i3 = 1; }
else  { i3 = 0; }
}
i3 = i3 + 5 * (Math.floor( ((Decimal) startdt.daysBetween(enddt)).divide(7,4))).intValue();
if (tempdate != null) i3 *= -1; // negative number of days
return i3;
}

priyaforsfdc

it was not workin proper way?

venk1255

Hi Priya,

You can use this formula field to calculate busineesdays between the staring date and ending date,

5*FLOOR((
CASE(MOD(SSD__c-DATE(1900,1,7)

,7),
1,SSD__c,
2,SSD__c,
3,SSD__c,
4,SSD__c,
5,SSD__c,
6,SSD__c-1,
0,SSD__c-2,
SSD__c)
-CASE(MOD(Today()-DATE(1900,1,7),7),
1,Today(),
2,Today(),
3,Today(),
4,Today(),
5,Today(),
6,Today()-1,
0,Today()-2,
Today()))/7)

+MOD(
CASE(MOD(SSD__c-DATE(1900,1,7),7),
1,SSD__c,
2,SSD__c,
3,SSD__c,
4,SSD__c,
5,SSD__c,
6,SSD__c-1,
0,SSD__c-2,
SSD__c)
-CASE(MOD(Today()-DATE(1900,1,7),7),
1,Today(),
2,Today(),
3,Today(),
4,Today(),
5,Today(),
6,Today()-1,
0,Today()-2,
Today()),
7)

-IF(
CASE(MOD(Today()-DATE(1900,1,7),7),
1,1,
2,2,
3,3,
4,4,
5,5,
6,5,
0,5,
0)
<=
CASE(MOD(SSD__c-DATE(1900,1,7),7),
1,1,
2,2,
3,3,
4,4,
5,5,
6,5,
0,5,
0),
0,2)
Roger Wicki
@Surprise: I had to get rid of the check if tempDate == Null part to get it right. Because for me a difference in business days can not be negative... ;)