David Folksman
David Folksman

Reputation: 235

Comparing two Dates using strtotime() in PHP

I have two variables containing strings of dates in the format

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

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

Then I try to compare them like this,

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

Why does the code inside the IF statement never execute?

Upvotes: 6

Views: 17675

Answers (5)

Yohan M
Yohan M

Reputation: 1

In Europe, in particulary in France, we also use this format with the slash separator :

day/month/year

example for a french date : 26/08/2019

Upvotes: 0

Joyes Sebastian
Joyes Sebastian

Reputation: 1

The case of strtotime() function is the most easy way to handle using the format as yyyy-mm-dd. This is normal format in db date. If you use this format help easy for compare two dates.

Upvotes: 0

Robert
Robert

Reputation: 20286

I see you accepted answer but just to make sure you understand. There are 2 cases that dates are parsed.

  1. American - month/day/year
  2. European - day.month.year or day-month-year

You have error because you provided european format "07-14-2013" and there's no 14 month in year.

The proper format for you is one of these:

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

Morover, to compare datatime it's better to use object oriented solution and DataTime object. You can read more here.

Upvotes: 3

Daniel
Daniel

Reputation: 18672

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

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

From the manual:-

Dates in the m/d/y or d-m-y formats are disambiguated by looking at 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 dot (.), then the European d-m-y format is assumed.

Upvotes: 8

alex
alex

Reputation: 490273

The format (when used like that) is DD-MM-YYYY. There is no 14th month.

Upvotes: 2

Related Questions