Many times we have to check the date entered are in correct format or not. The combination of entered month date and year by a user has to be a valid date to use in our applications. Even if we give a selection or a drop down list box to select a date we have to check the combination of month, day and year selection is valid or not. User may select 29th Feb 2005 (which is not a leap year ) or it may select 31st Nov of any year. So the combination has to be checked.
Using checkdate()
We will try checkdate() function which takes care of leap year checking also. This function validates the date and returns true if date is correct or false if date is wrong or does not exist. Here is the format
Here is the case where checkdate will return false
$m='11';
$d='31';
$y='05';
If(!checkdate($m,$d,$y)){
echo 'invalid date';
}else {
echo "Entry date is correct";
}
Input date from a text field
If we are asking the user to enter date in a text field then we have to break the entered date value by using explode function and then use the checkdate function to validate the date data ( of user ). Here we are collecting the user entered date value of a form posted by POST method.
$dt=$_POST['dt'];
$dt="02/28/2007"; // Setting a date in m/d/Y format
$arr=explode("/",$dt); // breaking string to create an array
$mm=$arr[0]; // first element of the array is month
$dd=$arr[1]; // second element is date
$yy=$arr[2]; // third element is year
If(!checkdate($mm,$dd,$yy)){
echo "invalid date";
}else {
echo "Entry date is correct";
}
If your input format is different then you can change the variables after creating the array by.
$dd=$arr[0]; // first element of the array is date
$mm=$arr[1]; // second element is month
$yy=$arr[2]; // third element is year
Input date from a calendar
We don't expect a wrong entry by user when they select a date from a Calendar. However it is better to check the date as user can change the dates after selecting from a calendar by using the above code for textbox.
$date = DateTime::createFromFormat('d/m/Y', '01/13/2019');
// change above input date for different messages. //
$errors = DateTime::getLastErrors();
if (!empty($errors['warning_count'])) {
echo "Strictly speaking, input date is invalid! ( Warning ) ";
}
if (!empty($errors['error_count'])) {
echo "input date is invalid! ( error ) ";
}
//echo "<br>Input date is : ".$date->format('Y-m-d H:i:s');
$date = DateTime::createFromFormat('d/m/Y', '01/13/2019');
Strictly speaking, input date is invalid! ( Warning )
Input date is : 2020-01-01 12:34:34
$date = DateTime::createFromFormat('d/m/Y', 'Wrong data');
input date is invalid! ( error )