machineaddict
machineaddict

Reputation: 3236

Is comparing MySQL dates string formats in PHP correct?

I have been comparing mysql dates in php by doing this:

<?php

strtotime('2007-12-12 10:00:01') > strtotime('2007-12-12 10:00:00')

I just found out that if you compare 2 dates (format Y-m-d H:i:s) in php directly, that the result seems to be ok. I've searched google for this, no results were found.

Example 1:

<?php

var_dump('2006-12-12 10:00:00' > '2006-12-12 10:00:00');
var_dump('2006-12-12 10:00:00' >= '2006-12-12 10:00:00');
var_dump('2006-12-12 10:00:00' <= '2006-12-12 10:00:00');
var_dump('2006-12-12 10:00:00' < '2006-12-12 10:00:00');

Result 1:

bool(false)
bool(true)
bool(true)
bool(false)

Example 2:

<?php

var_dump('2007-12-12 10:00:00' > '2006-12-12 10:00:01');
var_dump('2007-12-12 10:00:00' >= '2006-12-12 10:00:01');
var_dump('2007-12-12 10:00:00' <= '2006-12-12 10:00:01');
var_dump('2007-12-12 10:00:00' < '2006-12-12 10:00:01');

Result 2:

bool(true)
bool(true)
bool(false)
bool(false)

It appears that php is comparing 2 mysql dates correctly. Is this a correct way of comparing mysql dates in php?

Upvotes: 1

Views: 69

Answers (1)

deceze
deceze

Reputation: 522332

'2007-12-12 10:00:00' > '2006-12-12 10:00:01' compares two strings lexically. This incidentally happens to work if both strings have the same format (i.e. numbers and hyphen or colons in the exact same spots) and if the order of elements is most-significant to least-significant (i.e. year, month, day, hour, minute, seconds).

So, jein. It's not incorrect since it actually does work, but the fact that is does work is more or less incidental. It simply seems like a brittle solution which could easily break, while explicitly parsing the date using strtotime and comparing explicit timestamp values is a lot less brittle. (Note that strtotime also depends on the string being a certain know format though, it won't magically parse any and all values for you.)

Upvotes: 4

Related Questions