How to compare dates in PHP?

Question:

I would like to know which function I use to compare two dates and return the largest one.

I have a form for HR registration in which the user will register their professional experiences and the date of entry into the job cannot be greater than the date of exit, so I need to check this condition and return false.

Someone would have a suggestion on how to solve this I found some solutions but the date format was in American standard which does not suit me. Att.

Answer:

In order to work with date first of all we have to keep in mind that the standard used is the American standard which requires us to use the Year-Month-Day format (Ex.: 2013-05-22).

In our example we are going to create a script that compares if date1 is greater than or equal to date2 and displaying the corresponding messages.

<?php
 $data1 = '2013-05-21';
 $data2 = '2013-05-22';

 // Comparando as Datas
 if(strtotime($data1) > strtotime($data2))
 {
  echo 'A data 1 é maior que a data 2.';
 }
 elseif(strtotime($data1) == strtotime($data2))
 {
  echo 'A data 1 é igual a data 2.';
 }
 else
 {
  echo 'A data 1 é menor a data 2.';
 }
?>

Obs.: The command strtotime generates the timestamp of a date in text format so that we can work with the dates.

For the standard conversion, it can be done like this:

$dataString = '19/03/2013 11:22';
$date = DateTime::createFromFormat('d/m/Y H:i', $dataString);
echo $date->format('Y-m-d H:i:s');

And of course it must be tailored to your needs.

Scroll to Top