Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Date Question

Tags:

date

php

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)

like image 254
Señor Reginold Francis Avatar asked Jun 25 '09 14:06

Señor Reginold Francis


2 Answers

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';
like image 53
Greg Avatar answered Oct 12 '22 01:10

Greg


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

like image 27
chaos Avatar answered Oct 12 '22 01:10

chaos