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

PhpDateTimeStrtotime

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

First. You have mistake in using function strtotime see PHP documentation

int strtotime ( string $time [, int $now = time() ] )

You need modify your code to pass integer timestamp into this function.

Second. You use format d.m.Y H:i that includes time part. If you wish to compare only dates, you must remove time part, e.g. `$date = date("d.m.Y");``

Third. I am not sure if it works in the same way for you, but my PHP doesn't understand date format from $timestamp and returns 01.01.1970 02:00 into $match_date

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

You need to check if strtotime($timestamp) returns correct date string. If no, you need to specify format which is used in $timestamp variable. You can do this using one of functions date_parse_from_format or DateTime::createFromFormat

This is a work example:

$timestamp = "2014.09.02T13:34";

$today = new DateTime("today"); // This object represents current date/time with time set to midnight

$match_date = DateTime::createFromFormat( "Y.m.d\\TH:i", $timestamp );
$match_date->setTime( 0, 0, 0 ); // set time part to midnight, in order to prevent partial comparison

$diff = $today->diff( $match_date );
$diffDays = (integer)$diff->format( "%R%a" ); // Extract days count in interval

switch( $diffDays ) {
    case 0:
        echo "//Today";
        break;
    case -1:
        echo "//Yesterday";
        break;
    case +1:
        echo "//Tomorrow";
        break;
    default:
        echo "//Sometime";
}

Solution 2 - Php

<?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';
 }	
?>

Solution 3 - Php

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
}

Solution 4 - Php

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.

Solution 5 - Php

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;
		}
	}
}

Solution 6 - Php

Simple one liners for today/yesterday/tomorrow:

$someDate = '2021-11-07'; // date in any format

$isToday = date('Ymd') == date('Ymd', strtotime($someDate));
$isYesterday = date('Ymd') == date('Ymd', strtotime($someDate) + 86400);
$isTomorrow = date('Ymd') == date('Ymd', strtotime($someDate) - 86400);

Solution 7 - Php

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";
					}
				}
			?>

Solution 8 - Php

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

Solution 9 - Php

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;
}
?>

Solution 10 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionR2D2View Question on Stackoverflow
Solution 1 - PhpNicolaiView Answer on Stackoverflow
Solution 2 - PhpNithView Answer on Stackoverflow
Solution 3 - PhpZeusarmView Answer on Stackoverflow
Solution 4 - PhpThomas DecauxView Answer on Stackoverflow
Solution 5 - PhpBVB MediaView Answer on Stackoverflow
Solution 6 - PhpShahroqView Answer on Stackoverflow
Solution 7 - Phpthe_haystackerView Answer on Stackoverflow
Solution 8 - PhpmarcusView Answer on Stackoverflow
Solution 9 - PhpPoojaView Answer on Stackoverflow
Solution 10 - PhpOlogunde OlawaleView Answer on Stackoverflow