PHP 中的日期比较
我目前有一个日期作为 255 个字符的 VARCHAR 存储在我的 SQL 数据库中。我将此字符串声明为
//within an object...
$date = date(DATE_RFC822);
“现在”,稍后在编码中,我意识到我需要实际相互比较日期。我最初的、非常天真的尝试看起来有点像这样:
if(object_1->date > object_2->date){
//do this that assumes that object_1 was created at a later date than object_2
}else{
continue;
}
虽然这在同一天的不同时间都效果很好;一周后使用该代码开始显示出严重的错误。
I currently have a date that's being stored in my SQL database as a VARCHAR of 255 characters. I declared this string as
//within an object...
$date = date(DATE_RFC822);
Now, later on in the coding, I realise that I need to actually compare dates with each other. My initial, very naive attempt looked a little bit like this:
if(object_1->date > object_2->date){
//do this that assumes that object_1 was created at a later date than object_2
}else{
continue;
}
While this worked fine for different times of the same day; using the code a week later began to show significant bugs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
strtotime()
将字符串转换为unix 时间(整数),可以轻松地与其他 unix 时间值进行比较。如果您运行的是 PHP 5.2.8 或更高版本,您还可以使用 DateTime 类相对容易比较(参见此问题了解更多信息)strtotime()
converts a string into unix time (an integer) which can easily be compared with other unix time values. If you are running PHP 5.2.8 or greater, you could also make use of the DateTime class which are relatively easy to compare (see this question for more info)您无法相互比较 DATE_RFC822 格式的日期。您应该在 MySQL 中使用 Date 或 DateTime 字段,在 PHP 中使用 DateTime 或 Unix 时间戳。在 PHP DateTime 构造函数或 strtotime() 中使用 DATE_RFC822 字符串是安全的。 (不过,如果您在 MySQL 中使用 Date 或 DateTime,您还可以按日期排序和按日期搜索等)
PHP DateTime 对象可以像普通 PHP 变量一样相互比较,因此您可以执行
$date1
$date1
$date1
$date1
$date1 $date2
确定$date1
是否在$date2
之前。You can't compare dates in DATE_RFC822 format with each other. You should use Date or DateTime fields in MySQL and DateTime or Unix timestamps in PHP. It's safe to use your DATE_RFC822 string in the PHP DateTime constructor or in strtotime(). (Still, if you use Date or DateTime in MySQL you can also sort by date and search by date, etc.)
PHP DateTime objects can be compared with each other like normal PHP variables, so you can do
$date1 < $date2
to determine if$date1
is before$date2
.