php

How to compare two dates in PHP

In this tutorial, we are going to see how to compare two dates in PHP. Given two dates (date1 and date2) and the task is to compare the given dates. Comparing two dates in PHP is simple when the two dates are in the same format, but the problem arises when the two dates are in a different format.
 

Method 1: How to compare two dates in PHP

If the given dates have the same format, use a simple comparison operator to compare the dates.

<?php 
	$date1 = "2010-01-15";
	$date2 = "2020-12-14";  

	if ($date1 < $date2) 
		echo "$date1 is less than $date2"; 
	else
		echo "$date1 is greater than $date2";
?>

Output:

2010-01-15 is less than 2020-12-14

 

 

Method 2: How to compare two dates in PHP

If the two given dates are in different formats, use the strtotime() function to convert the given dates into the corresponding “timestamp” format and finally compare them to get the desired result.

<?php 
	$date1 = "2010-01-15"; 
	$date2 = "2020-12-14"; 

	$timestamp1 = strtotime($date1); 
	$timestamp2 = strtotime($date2); 

	if ($timestamp1 > $timestamp2)
		echo "$date1 is greater than $date2";
	else
		echo "$date1 is less than $date2"; 
?>

Output:

2010-01-15 is less than 2020-12-14
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *