2

All across my php code i'm storing dates and times in UTC, but i'm also using mysql to store datetimes (also in utc).

is there any way that date comparisons can fail with the greater than and less than operator?

        $curdate=date('Y-m-d H:i:s');
        if($start_datetime>$curdate)
siliconpi
  • 8,105
  • 18
  • 69
  • 107

5 Answers5

7

Nope.
There is no way for them to fail.
Mysql date format is intentionally made for this purpose.

There is not a single reason to convert it in whatever else format to compare.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
3

PHP: change date into UNIX timestamp using strtotime() and then u can compare.


MySQL:

change dataType of date column to DateTime and then u can compare below way:

$d1 = new DateTime('2008-08-03 14:52:10');
$d2 = new DateTime('2008-01-03 11:11:10');

var_dump($d1 == $d2);
var_dump($d1 > $d2);
var_dump($d1 < $d2);
xkeshav
  • 53,360
  • 44
  • 177
  • 245
  • Me too. Also you can safely compare Y-m-d H:i:s datetimes in php - and they won't even suffer from the unix timestamp's 2038 bug. – cbrandolino Apr 04 '11 at 12:54
  • There is no need to convert the times to DateTime. You can directly compare date strings in the 'Y-m-d H:i:s' format by just using the regular "<" and ">" operators. PHP will compare the strings alphabetically, which produces accurate results when comparing time strings in this format (it also works with YYYY-MM-DD dates). – orrd May 27 '14 at 17:15
  • about timestamp, you might want to read this http://stackoverflow.com/a/7229760/2652018 – Steel Brain Aug 02 '14 at 09:07
0
strtotime($curdate) < strtotime($start_datetime)

strtotime() returns a int rperesenting the Seconds that passed since 01.01.1970 That means if $curdate date is "2011-01-01 12:00:00" and $start-datetime is "2011-01-01 12:00:01" then $start-datetime is bigger then $curdate because strtotime returns an integer for $start-datetime that is exactly one bigger than $curdate.

ITroubs
  • 11,094
  • 4
  • 27
  • 25
0

A direct datetime compare won't fail. You can do that.

A timestamp comparison would be faster, but I don't think such a micro-improvement in performance would be something to look for in a php application, plus you'll have to take into account the 2030 bug.

cbrandolino
  • 5,873
  • 2
  • 19
  • 27
0

I prefer to compare the 'Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)'. Of course, this is only good for dates on/after 1970.

Given that $date1 and $date2 are two date variables to compare:

if (date("U",$date1) > date("U",$date2)) {
  // $date1 is more recent than $date2
} else {
  // $date1 is older than (or equal to) $date2
}
Teddy
  • 18,357
  • 2
  • 30
  • 42