A
A
abricos072016-01-14 11:40:16
PHP
abricos07, 2016-01-14 11:40:16

Features of date comparison in php?

I know it's not a fair comparison. I would like to know why this is the result. Why does the result show that the first date is less than the second? I understand that he most likely casts these lines to some kind of scalar type. But to which one exactly? And why?

(date('01.01.2016') < date('25.12.2015')) === true

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2016-01-14
@abricos07

string date ( string $format [, int $timestamp = time() ] )

Because you're using the date() function incorrectly , it's just strings that are being compared. Strings are compared character by character. Zero is less than two, so the comparison immediately returns true.
The correct way to compare dates is:
$first = DateTime::createFromFormat('d.m.Y', '01.01.2016');
$second = DateTime::createFromFormat('d.m.Y', '25.12.2015');
var_dump($first < $second);

Or like this:
var_dump(strtotime('01.01.2016') < strtotime('25.12.2015'));

A
Andrey, 2016-01-14
@VladimirAndreev

the first parameter is the date format.
everything that is not included in the known modifiers is interpreted as a number.
in string comparison the second is greater than the first...
try strtotime and date format - YYYY-MM-DD

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question