简体   繁体   中英

PHP days left and gone from date

I want to get a user registered date, count the days since registration and show max days left to given days and show message after period ends.

What I got so far works:

$regDatestr = '2020-04-09 19:38:10';
$regDate = strtotime($regDatestr);
$regSince = time() - $regDate;
$days = round ($regSince / ( 60 * 60 * 24 ));
$maxDays = 20;
$maxDaysstr = strtotime("-$maxDays days");
$maxReg = ($regSince + $maxDaysstr); 
$daysleft =  time() - $maxReg;
$restDays = round ($daysleft / ( 60 * 60 * 24 ));

if ($regdate <= $maxDaysstr) : 
    echo 'period ended'
else : 
    echo 'Registered since' . $days . ' .days . Rest days ' . $restDays . '
endif;

$daysleft and days gives me the right days. But the period doesnt end exact after 20 days.

What I need is max 20 days since registration date. So when

'2020-04-09 19:38:10';

plus 20 days should end the period at

'2020-04-29 19:38:10';

but it seems my if condition doesnt work as expected. So Im getting "Registered since 21 days. Rest days 0".

Why is that so?

Because you have an typo in with your variable names

if ($regdate <= $maxDaysstr) 

should be

if ($regDate <= $maxDaysstr)

and your code could be shorter

$regDatestr = '2020-04-01 19:38:10';
$regDate = new DateTime($regDatestr);

$diffToday = $regDate->diff(new DateTime());

$maxDays = 10;
$diffMax = $regDate->diff(new DateTime("-$maxDays days"));

if ($diffMax->invert == 0) :
    echo 'period ended';
else :
    echo 'Registered since ' . $diffToday->days . ' .days . Rest days ' . $diffMax->days;
endif;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM