function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
DineshGuptaDineshGupta 

Apex logic to calculate no. of business days between two date-time fields (not date fields)

HI,

I need apex logic to calculate no.of business days between two date-time fields. I have seen so many posts but everyone are mentioning only workflow logic but not apex logic.. (Assume Mon to Fri are business days)
Thanks in advance.. 
deva mullapudideva mullapudi
create a formula field to calcualte no of days between, two date time fields. if the date time fields are existed on object
DineshGuptaDineshGupta
@deva:
Here, my requirement is to plugin the logic in controller, so I am looking for apex logic.
PS: Your formula gives only the no of days, not business days. 
DineshGuptaDineshGupta
@Prolay:
Checked the link, that would not give business days..
deva mullapudideva mullapudi
https://help.salesforce.com/HTViewSolution?id=000001100&language=en_US
Antonio ManenteAntonio Manente

I had a similar requirement recently so I'll share my solution.
Refer to this link: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_businesshours.htm#apex_System_BusinessHours_diff

First, you can create a BusinessHours object. Here, you can set what your business days/hours are. Once you have that, you can use the
BusinessHours.diff(BUSINESS_HOURS__ID, DATETIME1, DATETIME2)

 method which will return to you the total number of Business hours that have elapsed between two DateTime objects. If I'm not mistaken this method returns the value in miliseconds, which you can then convert to days.


P.S.

Don't convert milliseconds to days using 24hrs, you'd do the conversion with whatever length each business day is according to you business hours object.