sunil satpute
sunil satpute

Reputation: 111

date validation to compare two dates in php

i need to validate inputed date with database date. plz help..

Issue_date = 09-03-2015

return_date = 06-03-2015

I need my code select Issue_date from database and match with return_date ...If return_date < Issue_date then display error ..

This only accept if Issue_date and return_date are same OR return_date is greater than Issue_date

public function date_validation($book,$return_date)
        {
            $errors=array();                    
            $exists = $this->datab->prepare("SELECT issue_date FROM book_issue WHERE book_no = :book_no");
            $exists->execute(array(':book_no' => $book));
            $num_rows = $exists->fetch();   
            if($return_date < $num_rows['issue_date'])  
            { 
                $errors['Message'] = "Plz Select Return Date Greater Than Book Issue Date."; 
            }   

             return $errors;        
        } 

Upvotes: 0

Views: 987

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

Use the DateTime class, you can use the comparison operators on those:

$return_date = new DateTime($return_date);
$issueDate = new DateTime($num_rows['issue_date']));
if ($return_date < $issueDate) {
}

Job done. As an added bonus, you can force the caller of the function to pass a valid date to your function using a type-hint:

function dateValidation($book, DateTime $returnDate)
{
    //this function can only be called if $returnDate was an instance of DateTime
}

To display the actual date, simply use DateTime::format, and use the format you want:

echo $date->format('Y-m-d H:i:s');//yyyy-mm-dd hh:mm:ss
echo $date->format('d/m/y');//dd/mm/yy

Upvotes: 1

Related Questions