1

For example, if the first of the month is a Saturday, then I'd like to know the 3rd is the first business day of the month. Likewise for the last day of the month.

1
  • 4
    Welcome to SFSE! Please take the tour and read How to Ask. Questions of the form "Can I do X?" are usually not as good as a question like "I'm trying to do X, and am stuck on this part. How can I move forward?". You may get some response to your question as-is, but the community here generally likes to see that you've made an effort to research/solve your problem before coming to ask a question. In this case, sharing with us the code that you've developed up to this point would likely satisfy that. The more details you can provide, the more accurate the answers you'll tend to get.
    – Derek F
    Jan 31 '19 at 21:37
3

You can use BusinessHour class in apex to get first and last business day of the month.

For First Day :

// Get the default business hours
BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];

// Create Datetime .
Datetime targetTime = Datetime.newInstance(2018, 2, 1, 0, 0, 0);
// Starting from the targetTime, find the next date when business hours reopens. Return the target time.

// if it is within the business hours. The returned time will be in the local time zone
Datetime nextStart = BusinessHours.nextStartDate(bh.id, targetTime);

Get Last Date :

// Get the default business hours
BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];

// Create Datetime .
Datetime targetTime = Datetime.newInstance(2019, 3, 1, 0, 0, 1);

// Starting from the targetTime, find the next date when business hours reopens. Return the target time.

Date lastDate =  targetTime.addMonths(1).date().toStartOfMonth().addDays(-1); // Last day of month

while(true){

    if(BusinessHours.isWithin(bh.Id,lastDate)){
        break;
    }
    lastDate = lastDate.addDays(-1);

}

System.debug(lastDate);

Src: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_businesshours.htm

2
  • 1
    Seems like the second algorithm could be cleaned up a bit. I'm not a big fan of while (true) but you could probably at least remove else since it will only execute if the if condition is false anyway.
    – Adrian Larson
    Jan 31 '19 at 22:00
  • Thanks, @AdrianLarson, I missed it. I kinda thought about using recursion, but for sake of simplicity stuck with while(true) Jan 31 '19 at 22:04

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