Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: date "Yesterday", "Today"

Tags:

php

datetime

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?

like image 729
Karem Avatar asked Aug 10 '10 23:08

Karem


People also ask

How to get today yesterday in PHP?

Using time() to Get Yesterday's Date in PHP The time() function returns the current timestamp. If we subtract its value, then we get the timestamp of the same time yesterday.

How do you check the date is today or not in PHP?

Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.

How can I get tomorrow date in PHP?

$newDate = date('Y-m-d', strtotime('tomorrow')); echo $newDate; ?>


2 Answers

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.

Actually, I just tested this code and it seems to work great:

<?php
    if ($last_access >= strtotime("today"))
        echo "Today";
    else if ($last_access >= strtotime("yesterday"))
        echo "Yesterday";
?>
like image 81
Hameed Avatar answered Oct 02 '22 15:10

Hameed


function get_day_name($timestamp) {

    $date = date('d/m/Y', $timestamp);

    if($date == date('d/m/Y')) {
      $date = 'Today';
    } 
    else if($date == date('d/m/Y',now() - (24 * 60 * 60))) {
      $date = 'Yesterday';
    }
    return $date;
}
print date('G:i:s', $last_access).' '.get_day_name($last_access);
like image 45
Keyo Avatar answered Oct 02 '22 14:10

Keyo