Compare Date and Time in PHP

It is often necessary to compare date and time values in PHP, for example when checking if a certain event has occurred yet or not. The easiest way to do this is by using the built-in strtotime() and maketime() functions.

if ( strtotime('2022-05-20') > strtotime(date('Y-m-d', mktime(0, 0, 0, 5, 21, 2022))) )
   // do something
}
$today = strtotime("today");
$christmas = strtotime("December 25");
if ($today < $christmas) {
  echo "It's before Christmas!";
} else {
  echo "It's after Christmas.";
}
if (new DateTime('2020-05-25') < new DateTime()){
	echo 'Expiration date';
}

The strtotime() function converts a date/time string into a timestamp, which can then be compared with other timestamps.

The mktime() method is a useful method for working with dates in PHP. It returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified. The mktime() method can be used to calculate timestamps for use in date/time functions, or to convert between different time formats. It is also useful for generating sequential IDs, such as invoice numbers or order IDs. The mktime() method is easy to use and can be a valuable addition to any PHP developer’s toolkit.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close