Jump to content

Recommended Posts

Hi, I have this code :-

$datestarted = $row['datestarted'];
$datestart=date("l d/m/Y @ H:i:s",strtotime($datestarted)); 

Which is been echo'd like this :-

echo '
<tr align="center"'.$rowbackground.'>
<td>'.$datestart.'</td>							
<td align="center">
';

So for example I get this output :-Sunday 18/04/2021 @ 10:45:26

The data in the DB for the above is stored like this :-2021-04-18 10:45:26

 

What I'd like to do is also echo how many days ago this date was, all of the examples I've tried don't seem to work though?

Take your pick, sql or php solution?

$theDate = '2021-04-18 10:45:26';

$d1 = new DateTime($theDate);
$elapsed = $d1->diff(new DateTime())->days;
echo $elapsed;                                 //--> 23

or
 

SELECT datestarted
     , datediff(CURDATE(), datestarted) as elapsed
FROM ...

 

Take a look at the manual page for the Datetime::diff method.  What you are returned is a "DateInterval" object.

All you need to do is call the format method and utilize the appropriate format string -- it has already computed an internal representation of the interval between the 2 dates, and you don't want or need to do additional math to get this represented in days/hours/minutes etc.  Just look at the format strings.

the properties of the DateInterval object that you will need are

->days
->h
->i

so you will have some calculation but it's not rocket science.

Note there is also a "d" property but that is the number of days as in "Difference = 5 months 3 days 6 hrs"

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.