简体   繁体   English

在PHP中比较MySQL日期字符串格式是否正确?

[英]Is comparing MySQL dates string formats in PHP correct?

I have been comparing mysql dates in php by doing this: 我一直在通过比较php中的mysql日期:

<?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. 我只是发现,如果直接在php中比较2个日期(格式Ymd H:i:s ),结果似乎还可以。 I've searched google for this , no results were found. 我已经在Google上搜索了此内容 ,但未找到结果。

Example 1: 范例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: 结果1:

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

Example 2: 范例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: 结果2:

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

It appears that php is comparing 2 mysql dates correctly. 看来php正在正确比较2个mysql日期。 Is this a correct way of comparing mysql dates in php? 这是比较php中mysql日期a正确方法吗?

'2007-12-12 10:00:00' > '2006-12-12 10:00:01' compares two strings lexically . '2007-12-12 10:00:00' > '2006-12-12 10:00:01'比较两个字符串 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. 看起来这似乎很容易折断,而使用strtotime显式地解析日期并比较显式的timestamp值却不那么容易。 (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.) (请注意, strtotime还取决于字符串是否为某种已知格式,它不会为您神奇地解析任何和所有值。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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