Home >Backend Development >PHP Tutorial >How to Compare Dates with a Custom 'd_m_y' Format in PHP?

How to Compare Dates with a Custom 'd_m_y' Format in PHP?

DDD
DDDOriginal
2024-12-29 16:31:11448browse

How to Compare Dates with a Custom 'd_m_y' Format in PHP?

Comparing Dates in PHP with a Custom Format

Question:

How can I compare two dates in PHP that are formatted as '03_01_12' and '31_12_11'?

Attempt 1:

The provided code:

$date1 = date('d_m_y');
$date2 = '31_12_11';
if (strtotime($date1) < strtotime($date2))
    echo '1 is small ='.strtotime($date1), ','.$date1;
else
    echo '2 is small ='.strtotime($date2), ','.$date2;

Explanation:

The above code attempts to compare dates using the strtotime() function, but it's not working because it uses the system's default date format for conversion, which is not the custom format used in the date strings.

Answer:

To properly compare the dates with the given custom format, you can use the DateTime::createFromFormat() method. Here's a modified code example:

$format = "d_m_y";
$date1  = \DateTime::createFromFormat($format, "03_01_12");
$date2  = \DateTime::createFromFormat($format, "31_12_11");

var_dump($date1 > $date2);

In this code:

  • The $format variable defines the custom date format used in the date strings.
  • DateTime::createFromFormat(...) creates two DateTime objects from the date strings using the specified format.
  • The > operator compares the DateTime objects based on their timestamps, which are automatically converted to the same format.
  • The var_dump() function outputs the result of the comparison in a human-readable format.

The above is the detailed content of How to Compare Dates with a Custom 'd_m_y' Format in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn