How To Compare Any Format Date In PHP

In this article, We will learn about how to compare any format date in PHP.

We are use the PHP strtotime() Function.

strtotime() Function:

The strtotime() function is a built-in function in PHP that converts date or time-related strings into real date/time objects.

Which is used function is so powerful that it can parse virtually any DateTime-related English text to Unix timestamp and also The function accepts a string parameter in English which represents the description of date-time.

Syntax:

strtotime( $datetime, $timenow);

Parameters:

  • $datetime: Required. Specific a valid format date/time string.
  • $timenow: Optional. The timestamp is used as a base for the calculation of relative dates.

Return Values:

Returns a timestamp on success, false otherwise.

The below program demonstrates converting into the strtotime() of different format dates and then comparing these timestamp strings.

<?php 
  $date1 = "12-03-26";
  $date2 = "2011-10-24";

  $date3 = "+1 week 3 days 7 hours 5 seconds";
  $date4 = "next Monday";

  $date5 = "3 October 2005";
  $date6 = date( "Y/m/d" ) ;
  echo strtotime( "25/	05/2010" );
  //Use strtotime() function to convert
  //date into datetimestamp
  $datetimestamp1 = strtotime( $date1 );
  $datetimestamp2 = strtotime( $date2 );

  $datetimestamp3 = strtotime( $date3 );
  $datetimestamp4 = strtotime( $date4 );

  $datetimestamp5 = strtotime( $date5 );
  $datetimestamp6 = strtotime( $date6 );

  //Compare the timestamp date 
  echo '<h3>Compare the first condition:</h3>';
  if ( $datetimestamp1 > $datetimestamp2 ) {
    echo "$date1 is latest than $date2";
  } else {
    echo "$date1 is older than $date2";
  }

  echo '<h3>Compare the second condition:</h3>';
  if ( $datetimestamp3 > $datetimestamp4 ) {
    echo "$date3 is latest than $date4";
  } else {
    echo "$date3 is older than $date4";
  }

  echo '<h3>Compare the third condition:</h3>';
  if ( $datetimestamp5 > $datetimestamp6 ) {
    echo "$date5 is latest than $date6";
  } else {
    echo "$date5 is older than $date6";
  }
?>  

Now you can see the output of comparing different format dates.

Output:

Thank you, I hope you find something helpful.🙂

 

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories