php

How to Check Format of Date in PHP

In this tutorial, we are going to see how to check Date format in PHP. DateTime class is available in PHP versions above 5.2 and is very powerful. For example, it is very easy to check if a string represents a valid date or time, regardless of the format or time zone. In the example below, we will see how to validate the format of a date in PHP.

isValid() function checks if the given string is a valid date using PHP. It uses DateTime class of PHP to validate the date according to the specified format. This function returns TRUE if the date is valid, otherwise FALSE.
 

How to check format of Date in PHP
<?php
	function isValid($date, $format = 'Y-m-d'){
		$dt = DateTime::createFromFormat($format, $date);
		return $dt && $dt->format($format) === $date;
	}

	var_dump(isValid('2019-07-01'));
	var_dump(isValid('2020-21-03'));
?>

Output:

bool(true) 
bool(false)
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *