[php] PHP: How to check if a date is today, yesterday or tomorrow

I would like to check, if a date is today, tomorrow, yesterday or else. But my code doesn't work.

Code:

$timestamp = "2014.09.02T13:34";
$date = date("d.m.Y H:i");
$match_date = date('d.m.Y H:i', strtotime($timestamp));

if($date == $match_date) { 

    //Today

} elseif(strtotime("-1 day", $date) == $match_date) {

    //Yesterday

} elseif(strtotime("+1 day", $date) == $match_date) {

    //Tomorrow

} else {

    //Sometime

}

The Code always goes in the else case.

This question is related to php date time strtotime

The answer is


function getRangeDateString($timestamp) {
    if ($timestamp) {
        $currentTime=strtotime('today');
        // Reset time to 00:00:00
        $timestamp=strtotime(date('Y-m-d 00:00:00',$timestamp));
        $days=round(($timestamp-$currentTime)/86400);
        switch($days) {
            case '0';
                return 'Today';
                break;
            case '-1';
                return 'Yesterday';
                break;
            case '-2';
                return 'Day before yesterday';
                break;
            case '1';
                return 'Tomorrow';
                break;
            case '2';
                return 'Day after tomorrow';
                break;
            default:
                if ($days > 0) {
                    return 'In '.$days.' days';
                } else {
                    return ($days*-1).' days ago';
                }
                break;
        }
    }
}

Here is a more polished version of the accepted answer. It accepts only timestamps and returns a relative date or a formatted date string for everything +/-2 days

<?php

/**
 * Relative time
 *
 * date Format http://php.net/manual/en/function.date.php
 * strftime Format http://php.net/manual/en/function.strftime.php
 * latter can be used with setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
 *
 * @param  timestamp $target
 * @param  timestamp $base   start time, defaults to time()
 * @param  string $format use date('Y') or strftime('%Y') format string
 * @return string
 */
function relative_time($target, $base = NULL, $format = 'Y-m-d H:i:s')
{

    if(is_null($base)) {
        $base = time();
    }

    $baseDate = new DateTime();
    $targetDate = new DateTime();

    $baseDate->setTimestamp($base);
    $targetDate->setTimestamp($target);

    // don't modify original dates
    $baseDateTemp = clone $baseDate;
    $targetDateTemp = clone $targetDate;

    // normalize times -> reset to midnight that day
    $baseDateTemp = $baseDateTemp->modify('midnight');
    $targetDateTemp = $targetDateTemp->modify('midnight');

    $interval = (int) $baseDateTemp->diff($targetDateTemp)->format('%R%a');

    d($baseDate->format($format));

    switch($interval) {
        case 0:
            return (string) 'today';
        break;

        case -1:
            return (string) 'yesterday';
        break;

        case 1:
            return (string) 'tomorrow';
        break;

        default:
            if(strpos($format,'%') !== false )
            {
                return (string) strftime($format,  $targetDate->getTimestamp());
            }
            return (string) $targetDate->format($format);
        break;

    }
}

setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo relative_time($weather->time, null, '%A, %#d. %B'); // Montag, 6. August 
echo relative_time($weather->time, null, 'l, j. F'); // Monday, 6. August

function get_when($date) {

    $current = strtotime(date('Y-m-d H:i'));

    $date_diff = $date - $current;
    $difference = round($date_diff/(60*60*24));

    if($difference >= 0) {
            return 'Today';
    } else if($difference == -1) {
            return 'Yesterday';
    } else if($difference == -2 || $difference == -3  || $difference == -4 || $difference == -5) {
            return date('l', $date);
    } else {
            return ('on ' . date('jS/m/y', $date));
    }

}

get_when(date('Y-m-d H:i', strtotime($your_targeted_date)));

Pass the date into the function.

            <?php
                function getTheDay($date)
                {
                    $curr_date=strtotime(date("Y-m-d H:i:s"));
                    $the_date=strtotime($date);
                    $diff=floor(($curr_date-$the_date)/(60*60*24));
                    switch($diff)
                    {
                        case 0:
                            return "Today";
                            break;
                        case 1:
                            return "Yesterday";
                            break;
                        default:
                            return $diff." Days ago";
                    }
                }
            ?>

I think this will help you:

<?php
$date = new DateTime();
$match_date = new DateTime($timestamp);
$interval = $date->diff($match_date);

if($interval->days == 0) {

    //Today

} elseif($interval->days == 1) {
    if($interval->invert == 0) {
        //Yesterday
    } else {
        //Tomorrow
    }
} else {
    //Sometime
}

<?php 
 $current = strtotime(date("Y-m-d"));
 $date    = strtotime("2014-09-05");

 $datediff = $date - $current;
 $difference = floor($datediff/(60*60*24));
 if($difference==0)
 {
    echo 'today';
 }
 else if($difference > 1)
 {
    echo 'Future Date';
 }
 else if($difference > 0)
 {
    echo 'tomorrow';
 }
 else if($difference < -1)
 {
    echo 'Long Back';
 }
 else
 {
    echo 'yesterday';
 }  
?>

There is no built-in functions to do that in Php (shame ^^). You want to compare a date string to today, you could use a simple substr to achieve it:

if (substr($timestamp, 0, 10) === date('Y.m.d')) { today }
elseif (substr($timestamp, 0, 10) === date('Y.m.d', strtotime('-1 day')) { yesterday }

No date conversion, simple.


This worked for me, where I wanted to display keyword "today" or "yesterday" only if date was today and previous day otherwise display date in d-M-Y format

<?php
function findDayDiff($date){
   $param_date=date('d-m-Y',strtotime($date);
   $response  = $param_date;
   if($param_date==date('d-m-Y',strtotime("now"))){
       $response = 'Today';
   }else if($param_date==date('d-m-Y',strtotime("-1 days"))){
       $response = 'Yesterday'; 
   }
   return $response;
}
?>

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object

Examples related to strtotime

PHP: How to check if a date is today, yesterday or tomorrow PHP Converting Integer to Date, reverse of strtotime date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST PHP strtotime +1 month adding an extra month PHP, Get tomorrows date from date Adding three months to a date in PHP How to get previous month and year relative to today, using strtotime and date? Adding 30 minutes to time formatted as H:i in PHP $date + 1 year? adding 30 minutes to datetime php/mysql