Sony G
Sony G

Reputation: 128

How to compare two dates in d-M-Y format?

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;
}

Upvotes: 0

Views: 289

Answers (3)

Sharlike
Sharlike

Reputation: 1789

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;
}

Upvotes: 1

user428517
user428517

Reputation: 4193

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;
}

Upvotes: 2

Rikesh
Rikesh

Reputation: 26451

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;
}

Upvotes: 3

Related Questions