Date comparison in PHP

2019-03-02 05:25发布

问题:

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.