Difference between two PHP dates in 31, 28 and 29 day months

Asked

Viewed 1,489 times

2

I have a bonus system that only releases the bonus after 30 days of exact user registration. To compare the current date with the date of the user’s registration so that I get how many days to complete the exact 30 days, I use the following code PHP:

$time1 = new DateTime($user->date); //data do cadastro do usuário (MySQL timestamp)
$time2 = new DateTime(date("Y-m-d H:i:s")); //data atual
$interval =  $time2->diff($time1);
$faltam_dias = 30 - $interval->d;

Doubt:

I did this test in the current month (June) which contains exactly 30 days. If the current month has 31 or 28/29(February) days, how would you get correctly how many days would be left to complete the 30 days bonus?

2 answers

5


Use the property days instead of d:

$time1 = new DateTime('20150501'); 
$time2 = new DateTime(); //data atual
$interval =  $time2->diff($time1);
echo $interval->days;

http://ideone.com/zK0P2E

-2

Use +1 Month... instead of 30 days, it might make your code easier to use....

$data_inicial = 2017-07-01;
$data_final = date("Y-m-d", strtotime('+1 Month', $data_inicial));
echo $data_final;

I believe it will be printed:

2017-08-01

and I also believe that it will be possible to deliver 12 bonuses exactly per year

:)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.