Jump to content

Calculate number of days ago from timestamp


ohno
 Share

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?

Link to comment
Share on other sites

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 ...

 

Link to comment
Share on other sites

On a similar note, can the date string be converted to minutes rather than days? (in PHP that is).

 

I did try $elapsed = $d1->diff(new DateTime())->i ;

Link to comment
Share on other sites

This works but doesn't add any hours outside of the whole days :-

$elapsed = $d1->diff(new DateTime())->days * 24 * 60;

 

eg, if the elapsed time is 7 days two hours it gives 10080 minutes instead of 10200.

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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"

Link to comment
Share on other sites

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.

 Share

×
×
  • 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.