tags:

views:

254

answers:

6
+3  Q: 

PHP Date Question

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)

+1  A: 

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

chaos
Don't forget that PHP 5.3 isn't out yet (as of June 2009)
Greg
+6  A: 

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';
Greg
perfect. thanks a bunch
Steven1350
A: 

Use DateTime class and then you have a method diff.

Artem Barger
A: 

Try using date_parse.
From the manual:

<?php
print_r(date_parse("2006-12-12 10:00:00.5"));
?>

Will print

Array
(
    [year] => 2006
    [month] => 12
    [day] => 12
    [hour] => 10
    [minute] => 0
    [second] => 0
    [fraction] => 0.5
    [warning_count] => 0
    [warnings] => Array()
    [error_count] => 0
    [errors] => Array()
    [is_localtime] => 
)
Lawrence Barsanti
+2  A: 

Use the fact that times are stored in seconds:

 $days = floor(($shoutTime - time()) / 86400) + 1; // 86400 = 24*60*60

 switch ($days) { 
   case 0:
     return date('H:i', $shoutTime);
   case -1:
     return 'yesterday';
   case 1:
     return 'tomorrow';
 }

 return "$days ago";
Matijs
A: 

I don't think it's been pointed out that you can use strtotime to get "Yesterday". It makes it more readable (and easier to remember) than calculating dates "by hand" and is probably less error prone too.

$int = strtotime('Yesterday');


if(date('Y-m-d', $shoutTime) == date('Y-m-d') {
    return date('H:i:s', $shouTime);
} elseif(date('Y-m-d', $shoutTime) == date('Y-m-d', strtotime('Yesterday')) {
    return "Yesterday.";
} else {
  $days = floor($shoutTime - time() / 86400);
  return "$days ago.";
}
Eduardo Romero