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.
$newDate = date('Y-m-d', strtotime('tomorrow')); echo $newDate; ?>
Interval Between Different Dates In order to compare those two dates we use the method diff() of the first DateTime object with the second DateTime object as argument.
You can use the date function. I'm using strtotime to get the timestamp to that day ; there are other solutions, like mktime , for instance.
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"; }
<?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'; } ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With