Ketan Patel    08-Jun-2013

In this post we will see how to validate date in PHP. Date that you want to test may have various Formats Like:

  • YYYY-MM-DD
  • DD/MM/YYYY
  • MM-DD-YYYY
  • DD-MM-YYYY
  • YYYY-MM-DD and so on.

We will see mostly used formats. Date in the other format  can easily be validated by making small changes in the existing code. So, let’s have look at them.

 

YYYY-MM-DD Format

//Date that needs to be tested goes here
$date = '2013-05-14';

function isItValidDate($date) {
    if (preg_match("/^(\d{4})-(\d{2})-(\d{2})$/", $date, $matches)) {
	    if (checkdate($matches[2], $matches[3], $matches[1])) { 
	        return true;
	    }
	}
} 

if (isItValidDate($date)) {
   echo 'It’s a valid Date. '; 
} else {
  echo 'Entered Date is invalid..!!'; 
}

 

DD/MM/YYYY Format

//Date that needs to be tested goes here
$date = '14/05/2013'; 
 
function isItValidDate($date) {
    if (preg_match("/^(\d{2})\/(\d{2})\/(\d{4})$/", $date, $matches)) {
	    if (checkdate($matches[2], $matches[1], $matches[3])) {
	       return true; 
	    }
    }
}

if (isItValidDate($date)) {
  echo 'It’s a valid Date';
} else {
 echo 'Entered Date is invalid..!!';
}

 

MM-DD-YYYY Format

//Date that needs to be tested goes here
$date = '05-14-2013'; 

function isItValidDate($date) {
    if (preg_match("/^(\d{2})-(\d{2})-(\d{4})$/", $date, $matches)) {
	    if (checkdate($matches[1], $matches[2], $matches[3])) {
	       return true;
	    }
	}
 }

if (isItValidDate($date)) {
   echo 'It’s a valid Date'; 
} else {
   echo 'Entered Date is invalid..!!';
}

 

About Ketan Patel

A Web Developer having 7+ years of experience in web development. Worked with Laravel-Lumen, CakePHP, CodeIgniter, Opencart to make sites for startup companies and small businesses. Apart from blogging, he likes to read Novels, Listening music and Net surfing.