I am trying to do a little bit of math using dates in PHP. I am modifying a shoutbox, and I want to implement the following functionality.
If post date = today, return time of post
else if date = yesterday, return "yesterday"
else date = X days ago
How would I use php's date functions to calculate how many days ago a timestamp is (the timestamp is formatted in UNIX time)
Try this:
$shoutDate = date('Y-m-d', $shoutTime);
if ($shoutDate == date('Y-m-d'))
return date('H:i', $shoutTime);
if ($shoutDate == date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'))))
return 'yesterday';
return gregoriantojd(date('m'), date('d'), date('y')) - gregoriantojd(date('m', $shoutTime), date('d', $shoutTime), date('y', $shoutTime)) . ' days ago';
In php 5.3.0 or higher, you can use DateTime::diff (aka date_diff()).
In pretty much any php, you can convert the dates to Unix timestamps and divide the difference between them by 86400 (1 day in seconds).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With