MySQL DATETIME 格式比较 - 是否需要 strtotime?
我一直在做一些事情......
$dt1 = '1000-01-01 00:00:00'; //really some val from db
$dt2 = '1000-01-01 00:00:10'; //another val maybe db maybe formatted
if(strtotime($dt1) > strtotime($dt2){
//do something
}
是否需要 strtotime?我可以对日期时间格式的字符串进行更直接的比较吗?
即
if($dt1 > $dt2){
//do something
}
这总是有效吗?
I've been doing something along the lines of..
$dt1 = '1000-01-01 00:00:00'; //really some val from db
$dt2 = '1000-01-01 00:00:10'; //another val maybe db maybe formatted
if(strtotime($dt1) > strtotime($dt2){
//do something
}
Is the strtotime needed? can i do a more direct comparison on the datetime formatted strings?
i.e.
if($dt1 > $dt2){
//do something
}
Will that always work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,字符串的字典顺序格式为
yyyy-mm-dd hh: ii:ss
按预期工作。您甚至可以像这样对日期进行排序。但
请记住,对于格式不正确的字符串,您将不会收到任何反馈。因此,如果可能存在格式错误的字符串,您最好也检查一下。如果这不是问题,则 string1>string2 就可以了。
编辑:你甚至可以让 MySQL 来做这项工作。这是否比在 php 中更好/等于/更差取决于您实际想要实现的目标。例如
印刷品
Yes, the lexicographical order of strings in the format
yyyy-mm-dd hh:ii:ss
works as intended. You could even sort dates like that.prints
But keep in mind that you will get no feedback for strings that are not in the right format. So, if it could be that there are malformed strings you'd better check that, too. If that is not a concern, string1>string2 is ok.
edit: You could even let MySQL do the work. If this is better/equal/worse to doing it in php depends on what you're actually trying to achieve. E.g.
prints
如果您使用
YYYY-MM-DD HH:MM:SS
格式以字符串形式存储日期,则可以使用字母顺序:它将与日期相同命令。这意味着字符串比较与日期比较具有相同的结果。
我想补充一点,不使用 UNIX 时间戳 会有一个优势:这些时间戳仅限于范围从 1970 年到 2038 年,因为它们存储在 32 位整数中,表示自 1970 年 1 月 1 日以来的秒数(根据您的系统,范围可能更宽 - 但不是无限的)
If you have dates stored in string, using
YYYY-MM-DD HH:MM:SS
format, you can use the alphabetical order : it'll be the same as dates order.Which means the comparisons on strings will have the same result as comparisons on dates.
I would add that there would be an advantage in not using UNIX timestamps : those are limited to a range that goes from 1970 to 2038, as they are stored on 32 bits integers that represent a number of seconds since 1970-01-01 (depending on your system, the range might be wider -- but not unlimited)
我通常使用 strtotime() 来安全地将日期作为时间戳值进行比较。
您可以通过编写 IF 语句并在其中一个中打印“statement 1 true”并在另一个中打印“statement 2 true”来进行检查。然后尝试更改 dt1 和 dt2 的值,看看结果如何。
I usually use strtotime() to be safe in comparing dates as a timestamp value.
You can check by writing both IF statements and printing 'statement 1 true' in one and 'statement 2 true' in the other. Then try changing the values of dt1 and dt2 and see how that plays out.