Comparing two dates using strtotime () in PHP

I have two variables containing date strings in the format

$four_days_have_passed = "07-14-2013"; $now = "07-10-2013"; 

I checked the output in FirePHP and the dates are correct.

Then I try to compare them,

 if (strtotime($now) < strtotime($four_days_have_passed)) { Do Stuff } 

Why is the code inside the IF statement never executed?

+4
source share
4 answers

If you want to use the MM / DD / YYYY format, you need the / separator.

 $four_days_have_passed = "07/14/2013"; $now = "07/10/2013"; 

From the manual : -

Dates in m / d / y or dmy formats are resolved ambiguously by considering the separator between the various components: if the separator is a slash (/), then the American m / d / y is assumed; whereas if the separator is a dash (-) or a period (.), then the European dmy format is assumed.

+5
source

The format (when using it) is DD-MM-YYYY. There is no 14th month.

+2
source

I see that you accepted the answer, but just to make sure you understand. There are two cases where dates are processed.

  • American - Month / Day / Year
  • European - day.month.year or day-month-year

You have a mistake because you provided the European format "07-14-2013" and there are no 14 months in a year.

The right format for you is one of the following:

  • 14-07-2013 - Europe
  • 14.07.2013 - Europe
  • 07/14/2013 - American

Morover, to compare a datatime, it is better to use an object-oriented solution and a DataTime object. You can read it here.

+2
source

The strtotime() function case is the easiest way to handle using the yyyy-mm-dd format. This is the normal format in db date. If you use this format, make it easy to compare two dates.

0
source

Source: https://habr.com/ru/post/1490597/


All Articles