简体   繁体   中英

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 Ymd 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?

'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 (ie numbers and hyphen or colons in the exact same spots) and if the order of elements is most-significant to least-significant (ie 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM