简体   繁体   中英

Days spent between now and n date [PHP]

Okay! so we all have seen how to get days remaining between NOW and a DATE in the future Like I have in my simple code below:

SAY: $endate = a date in future (5 days from today);

$start =  new DateTime();
$end = new DateTime($enddate);
$diff = $end->diff($start)->format('%a');
$days = intval($diff);
 
echo $days.'Days Remaining'; // 5 days Remaining

The above PHP Code is expected to show you how many days are left between NOW and the FUTURE DATE .

But what I want is the reverse of this situation. That is.

instead of having

5 Days Remaining

I need some thing like

0 Day(s) Spent //where today is day 0 of 5

$start = new DateTime("2021-12-14");

$now = new DateTime();

$now_diff = $now->diff($start)->format("%a");

print_r($now_diff.' Day(s) Spent');

Finding the number of days between two dates

CLUE TO ANSWER PROVIDED BY @KHIMAJI VALUKIYA in comment

The trick here is to set the start date not as current date but the actual date to start counting/calculating from. Then the end date should be set to the current date.

$start =  new DateTime($enddate); //date to start counting from
$end = new DateTime(); //current date
$diff = $end->diff($start)->format('%a');
$days = intval($diff);
echo $days.'Days Spent'; // 5 Days Spent

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