Calculating when the next payment is due, taking February into consideration

117 Views Asked by At

I am trying to create a program that notifies me the day a payment is due. I pretty much have an idea on how it's done but one issue remains. Let's say that the customer opened the account on 1/31/17. The next due date is 2/28/18(a month later). My code states that if today's day is less than the day the policy was opened, don't count it as a month (since a whole month has not passed) so it won't count it as a full month, even though it should.

This code I have works for almost all dates, except for the last day of February, or if the month ends on the 30th and the policy was opened on a 31st.

$today = time();        
$policy_opened = strtotime($policy_opened);
                
//number of months the policy has been opened                             
$year_opened = date('Y',$policy_opened);
$year_now = date('Y',$today);               
$month_opened = date('m',$policy_opened);
$month_now = date('m',$today);
$day_opened = date('d',$policy_opened );
$day_now = date('d',$today);
$months_since_opened = (($year_now - $year_opened) * 12) + ($month_now - $month_opened);
$months_since_opened = $months_since_opened + 1; //since it can't start with 0 months opened.
if($day_now < $day_opened){
    //this is in order to count it as one month only if a 'whole month' has passed by.
    $months_since_opened = $months_since_opened - 1;
}
                
1

There are 1 best solutions below

1
On

You can try native Datetime function for direct mont or day diffrence calculation here is code for month calculation. This give you month diffrence from two dates also

$policyOpen = "2017-12-01";
$toDay = "2017-12-31";

$smallDate = new DateTime($opened);
$bigDate = new DateTime($toDay);

$months_since_opened= $small->diff($big)->format("%m");



you can also get diffrent date related parameter as shown below
echo $diff->y; //this will give you year diffrence
echo $diff->m; //this will give you month diffrence
echo $diff->d; //this will give you day diffrence
echo $diff->h; //this will give you hours diffrence
echo $diff->i; //this will give you minute diffrence
echo $diff->s; //this will give you second diffrence