php

How To Validate Date in PHP

It is essential to check whether the date values are valid or invalid when working with the date values. If the date value is not taken in the correct format, then the wrong output will be generated. So, validating the date is a very crucial task for the application. The date value can be validated by using multiple functions in PHP. One is checkdate() function and another is createFromFormat() function that is under the DateTime class of PHP. The uses of these functions to validate date in PHP have been shown in this tutorial.

Date Validation by Using checkdate() Function

Using the checkdate() function is one of the ways to validate a date in PHP. The syntax of this function is given below.

Syntax:

bool checkdate(int $month, int $day, int $year)

This function has three arguments, and all arguments of this function are mandatory. It returns True if the date value is valid. Otherwise, it returns False. Different uses of the checkdate() function are shown in this part of the tutorial.

Example 1: Check the Validity of Different Types of Date

Create a PHP file with the following script that checks the validity of five dates using the checkdate() function. The var_dump() function has been used to check the output of the checkdate() function.

<?php

/*Check the validity of different types of date values */

//Invalid date
echo var_dump(checkdate(30,9,2022)), "<br/>";

//Valid date
echo var_dump(checkdate(12,16,2022)), "<br/>";

//Valid date
echo var_dump(checkdate(2,29,2020)), "<br/>";

//Invalid date
echo var_dump(checkdate(2,29,2022)), "<br/>";

//Valid date
echo var_dump(checkdate(9,7,2022));

?>

The following output will appear after executing the previous script:

Example 2: Print Message Based on the Output of checkdate() Function

Create a PHP file with the following script to check the returned value of the checkdate() function and print the message based on the returned value:

<?php

//Define the day, month, and year values
$day = 15;
$month = 10;
$year = 2022;

//Assign the return values
$valid = checkdate($month,$day,$year);

if ($valid)
    echo "$day-$month-$year date is valid.";
else
    echo "$day-$month-$year date is valid.";

?>

The following output will appear after executing the previous script:

Example 3: Check the Validity of the Date Taken From the User

Create a PHP file with the following script that will take a date of birth using an HTML form and check whether the date is valid or invalid using the checkdate() function.

<!--Declare form to take a month, day, and year values from the users -->

<form action="#" method="post">

  Enter your birthday:
    <br /><br />
    <input type="text" name="m" placeholder="Month" size=3>
    <input type="text" name="d" placeholder="Day" size=3>
    <input type="text" name="y" placeholder="Year" size=3><br /><br />
    <input type="submit" name="submit" value="Submit">


</form>

<?php

//Check whether the form is submitted or not
if(isset($_POST['submit']))
{
    $month = (int) $_POST['m'];
    $day   = (int) $_POST['d'];
    $year  = (int) $_POST['y'];
   
    //Check whether the date is valid or invalid
    $valid = checkdate($month, $day, $year);
 
    //Print message based on the returned value of the checkdate() function
    if ($valid)
        $msg = $day.'-'.$month.'-'.$year.' (dd-mm-yyyy) date is valid.<br>';
    else
        $msg = $day.'-'.$month.'-'.$year.' (dd-mm-yyyy) date is invalid.';

    //Print the message
    echo $msg;
}

?>

The following form will appear after executing the previous script:

The following message will appear after submitting the form with the birthdate value, 16-12-2006:

Date Validation Using createFromFormat() Function

Using the createFromFormat() function of the DateTime class is another way of checking the validity of a date. The syntax of this function is provided below:

Syntax:

DateTime date_create_from_format( string $format, string $time, DateTimeZone $timezone )

Or

DateTime DateTime::createFromFormat( string $format, string $time, DateTimeZone $timezone )

The first argument of this function is mandatory, and it is used to take the format string of the date and time. This function’s second argument is mandatory, and it is used to take the date, time, or date-time value. The third argument is optional and used to set the timezone. It returns a DateTime object on success and a False on failure. Different uses of this function have been shown in this part of the tutorial.

Example 4: Check Date Validity by Using createFromFormat() and format() Functions

Create a PHP file with the following script that will check whether a particular date is valid or invalid by using the createFromFormat() and format() functions. The createFromFormat() function has been used to create a DateTime object of a date value, and the format() function has been used to check the validity of the date value.

<?php

//Assign a date value as a string

$dateVal = "31-Sep-2022";

//Create date object by using the createFromFormat() function

$objDate = DateTime::createFromFormat('d-M-Y', $dateVal);

//Check the date is valid or invalid

if($objDate && $objDate->format('d-M-Y') == $dateVal)

    echo "$dateVal date is valid.";
else
    echo "$dateVal date is invalid.";

?>

The following output will appear after executing the previous script:

Example 5: Check Date Validity by Using createFromFormat() and getLastErrors() Functions

Create a PHP file with the following script that will check whether a particular date is valid or invalid by using the createFromFormat() and getLastErrors() functions. The createFromFormat() function was used to create a DateTime object of a date value. Then the getLastErrors() function was used to check the validity of the date value by checking the values of the array returned by this function.

<?php

if(isset($_GET['dt']))

{

    //Assign a date value as a string
    $dateVal = $_GET['dt'];
    //Generate formatted date
    $formattedDate = DateTime::createFromFormat('d-M-Y', $dateVal);

    //Read errors in a variable
    $errors = DateTime::getLastErrors();

    //Check for error
    if ($errors['warning_count'] != 0 or $errors['error_count'] != 0)
        echo "$dateVal is invalid.";
    else
        echo "$dateVal is valid.";
}
else
    echo "No date value has been given.";

?>

The following output will appear after executing the previous script if no date value is given in the URL parameter:

The following output will appear after executing the previous script if the 31-Sep-2022 date value is given in the URL parameter and it is invalid:

The following output will appear after executing the previous script if the 30-Sep-2022 date value is given in the URL parameter and it is valid:

Conclusion

Two ways of checking the date validity have been shown in this tutorial by using the checkdate() function and the createFromFormat() function of the DateTime class by using multiple examples. Hopefully, the PHP users can properly check the date validity after reading this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.