# Apex Business Hours calculation glitch

I have a salesforce org with business hours set up from 8AM - 6PM (10 hours).
Corporate holidays are on 25,26th Dec and 1st Jan.
I'm using the standard apex method BusinessHours.add() to calculate future dates and looks like I'm hitting a magic number. Everything works fine if I add less than 60 days to the current date. If I add 60 or more the date moves back. I don't see any typos in my code.

``````BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault = true];
DateTime startDate = DateTime.now();
System.debug('  1 working day '+startDate +' => '+chosenDate);
System.debug('  2 working days '+startDate +' => '+chosenDate);
System.debug('  58 working days '+startDate +' => '+chosenDate);
System.debug('  59 working days '+startDate +' => '+chosenDate);
System.debug('  60 working days '+startDate +' => '+chosenDate);
System.debug('  61 working days '+startDate +' => '+chosenDate);
``````

And the output

``````1  working day  2017-12-07 12:03:33 => 2017-12-08 12:03:00
2  working days 2017-12-07 12:03:33 => 2017-12-11 12:03:00
58 working days 2017-12-07 12:03:33 => 2018-03-02 12:03:00
59 working days 2017-12-07 12:03:33 => 2018-03-05 12:03:00
60 working days 2017-12-07 12:03:33 => *2017-09-15* 08:00:13 (59 days back)
61 working days 2017-12-07 12:33:49 => *2017-09-18* 08:30:13 (58 days back)
``````
• this is quite remarkable Dec 7, 2017 at 14:55

You've hit upon a problem, all right, but not what you expected; you're using an Integer to try add milliseconds, which means you're limited to about 2 billion before you end up going negative.

Consider the following code:

``````Integer t = 61*10*3600*1000;
System.debug(t);
``````

The output is:

``````08:08:18.1 (3611491)|USER_DEBUG|[2]|DEBUG|-2098967296
``````

So, to fix this, use a Long instead:

``````Long t = (Long)61*10*3600*1000;
System.debug(t);
``````

Output:

``````08:10:39.1 (3110947)|USER_DEBUG|[2]|DEBUG|2196000000
``````

``````chosenDate = BusinessHours.add(bh.Id, startDate, (Long)61*10*3600*1000);
``````chosenDate = BusinessHours.add(bh.Id, startDate, 61L*10*3600*1000);