# Calculating day/night pay rates

Hi - got a bit of a problem that is sort of doing my head in. :goof:

Say a business pays \$20/hour when a worker works between the hours of 8am and 8pm (a day rate) - and \$30/hour when they work between 8pm and 8am (night rate).

Shifts can be say 7am to 10am (1 hour @ \$30, 2 hours @ \$20), or 4pm until 2am (6 hours @ \$20, 6 hours @ \$30) or just simply 10am to 2pm (4 hours @ \$20).

Anyone got a solution to how to code this into a formula that works for all of those fringe cases (i.e. overlapping day/night rates).

I have available the start and end times of the shift as timestamps, as well as the total length of the shift.

Cheers - any help greatly appreciated!

The above code would still work, you’d just have to add a second entry to the table saying the person worked from 00:00 to 02:00 the next day, and end the first entry at 24:00.

EDIT:
I’m not positive, but I -think- it might still work even if you told it the end time was 26:00 … but i dont know how the strtotime function would handle 26:00 (cant hurt to test)… it should only break if someone worked from like 10PM til 9AM the next day.

Thanks - yep it does “sound” real easy - but it’s got a few little tricks. The main one being a shift that starts at 6pm and finishes at 2am, and also getting the hours into a nice array along with the “time” that can span over 2 days.

How are you storing the shifts? Start and End Hours?
fortunately, time is a positively increasing function.

if(\$start < '08:00') {
\$thirty =  ((\$end <= '08:00') ? strtotime(\$end) : strtotime('08:00')) - strtotime(\$start); //Seconds of time.
}
if(\$end > '08:00') {
\$twenty = ((\$end <= '20:00') ? strtotime(\$end) : strtotime('20:00')) - ((\$start >= '08:00') ? strtotime(\$start) : strtotime('08:00'));
}
if(\$end > '20:00') {
\$thirty += strtotime(\$end) - ((\$start >= '20:00') ? strtotime(\$start) : strtotime('20:00'));
}

someone come along behind me and do it cleaner than this. I know it’s possible.

Assuming I understand your question… you should be able to store the rates for each hour of the day in a db table, or just a simple array. Are there times when the person might work at odd start/end times, like 7:15 AM - 1:23 PM? Just split their timecard by the hour, and then apply the hourly rate for each hour/partial hour. There may be a more elegant way to handle it, but I’d probably just use strtotime to convert each time chunk, then apply the rate.