简体   繁体   中英

Comparing dates using php

Please could you tell me what is wrong in this code ?

$locked_date = date('d-M-Y');
$edit_date = '29-Apr-2013';
if($edit_date <= $locked_date){
echo $edit_date.' smaller then'. $locked_date;
}
else {
echo $edit_date.' bigger then'. $locked_date;
}

Use strtotime function which will convert it to Unix Timestamp,

if(strtotime($edit_date) <= strtotime($locked_date)){
    echo $edit_date.' smaller then'. $locked_date;
}
else {
   echo $edit_date.' bigger then'. $locked_date;
}

You can't compare dates formatted as strings like that. An easy way to check if a date occurs before or after another date is to convert them to Unix timestamps (which are just integers) first using strtotime :

$locked_date = date('d-M-Y');
$edit_date = '29-Apr-2013';

if(strtotime($edit_date) <= strtotime($locked_date)) {
    echo $edit_date.' smaller then'. $locked_date;
} else {
    echo $edit_date.' bigger then'. $locked_date;
}

Use strtotime function to compare unix timestamps:

$locked = time(); //current timestamp
$locked_date = date(d-M-Y);
$edit_date = '29-Apr-2013';
$edit = strtotime($edit_date);
if($edit <= $locked){
    echo $edit_date.' smaller then'. $locked_date;
}
else {
    echo $edit_date.' bigger then'. $locked_date;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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