tags:

views:

88

answers:

4

Hello. I have a little function that shows latest activity, it grab timestamp in unix format from the db, and then it echo out with this line:

 date("G:i:s j M -Y", $last_access)

Now i would like to replace the date (j M -Y) to Yesterday, and Today if the latest activity was within today, and same goes with Yesterday.

How can i do this?

+1  A: 

I would find the timestap for last midnight and the one before it, if $last_access is between the two timestamps, then display yesterday, anything greater than last midnight's timestamp would be today...

I believe that would be the quicker than doing date arithmetic.

Just tested this code and it works:

<?php
    if ($last_access >= strtotime("today"))
        echo "Today";
    else if ($last_access >= strtotime("yesterday"))
        echo "Yesterday";
?>
Hameed
Much cleaner than my answer +1
Keyo
+1  A: 
something like:

$now = time();

$last_midnight = $now - ($now % (24*60*60));

if ($last_access >= $last_midnight)
{
 print "Today";
}    
elseif ($last_access >= ($last_midnight-(24*60*60))
{
 Print "Yesterday";
}
tcrosley
@mvds: I didn't know you could use relative strings in strtotime. Nice. Some gotchas re PHP4 vs PHP5 though.
tcrosley
@tcrosley: I actually use it in some web based search service to allow the user to enter a sliding window: e.g. from "two months ago" to "today".
mvds
+1  A: 

If you are going down the road as suggested above, with unix timestamps for today / yesterday, have a look at strtotime, one of the greatest inventions of the 20th (or 21st?) century:

echo strtotime("yesterday"); // midnight
1281391200

echo strtotime("today"); // midnight
1281477600

echo strtotime("today, 1:30");
1281483000
mvds
+1  A: 
function get_day_name($timestamp) {
    $date = date('d/m/Y', $timestamp);
    if($date == date('d/m/Y')) {
      $day_name = 'Today';
    } else if($date == date('d/m/Y',now() - (24 * 60 * 60))) {
      $day_name = 'Yesterday';
    }
    return $date;
}
print date('G:i:s', $last_access).' '.get_day_name($last_access);
Keyo
i get error unexpected '{'
Karem
The `else if` line seems to be missing a `)`.
Maerlyn
Sorry, fixed that up for you Karem. I guess it worked out for you though.
Keyo