kevin3954 kevin3954 - 9 days ago 5
PHP Question

Adding to date in a while loop

I have a date that goes into a loop that the user specifies. The date will always come from the database formatted as a 'Y-m-d' string. I am aware that I can compare the strings directly as long as they are in that format, however, I have also tried using strtotime to convert the dates to compare them with no luck. I am trying to determine how many paycheck a user has before a payment is due

Here is what I have

$due_date = '2016-12-13';

//count paychecks set to zero and added to by loop
$paychecks = 0;

//users next paycheck ('Y-m-d' ALWAYS)
$next_payday = $user['next_payday']; //equal to '2016-12-02'

//how often they get paid (int)
$frequency = 14;

while(strtotime($next_payday) <= strtotime($due_date)){

//next_payday equals 1480654800 when coming into the loop
//due_date equals 1481605200 when coming into the loop

//add 14 days to the date
$next_payday = date('Y-m-d', strtotime("+" .$frequency." days"));;

//add to paychecks
$paychecks++;
}


The problem is that the loop never stops. It keeps going and going.

Thanks for any help anyone can give me.

Answer

Ah, be sure to use strtotime to get integers (representing number of seconds since the epoch) for comparison and multiply your frequency of days by the number of seconds in a day (86400):

$due_date = strtotime('2016-12-25');

//count paychecks set to zero and added to by loop
$paychecks = 0;

//users next paycheck (unixtime for comparison)
$next_payday = strtotime($user['next_payday']);

//how often they get paid (int)
$frequency = 14;

while($next_payday <= $due_date){

    //add 14 days to the date
    $next_payday += ($frequency * 86400);

    //add to paychecks
    $paychecks++;
}
Comments