Date comparison in PHP

狂风中的少年 提交于 2019-12-20 04:30:32

问题


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.


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/6987282/date-comparison-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!