Validate a Date in PHP – the Ultimate Guide

Validate a Date Format in PHP – Code Snippet

Here is a featured example that shows how to validate a date in PHP using DateTime methods.

function validateDateWithFormat($date, $format = 'd-m-Y')
{
   $d = DateTime::createFromFormat($format, $date);
   $errors = DateTime::getLastErrors();
 
   return $d && empty($errors['warning_count']) && $d->format($format) == $date;
      
}
 
$first_date = "09-09-2022"; //Expect true beacuse the date and the format is correct.
a
$second_date = "09/09/2022"; //Expect false beacuse the date is correct but the format is incorrect.
 
$third_date = "31-09-2022"; //Expect false beacuse the format is correct but the date is incorrect.
 
echo validateDateWithFormat($first_date) ? "{$first_date} is correct" : "{$first_date} is incorrect";
echo validateDateWithFormat($second_date) ? "{$second_date} is correct" : "{$second_date} is incorrect";
echo validateDateWithFormat($third_date) ? "{$third_date} is correct" : "{$third_date} is incorrect";
 
/*
OUTPUT
09-09-2022 is correct
09/09/2022 is incorrect
31-09-2022 is incorrect
*/

This example may not make sense if you’re unfamiliar with DateTime methods. No worries, because this article explains every bit. So fasten your seatbelts, and let’s take a journey through this article.

PHP DateTime Class for Validating Dates

PHP DateTime class features many useful functions that help developers in various scenarios. For a good grasp, consider reading official documentation or PHP DateTime by FuelingPHP. Nevertheless, the article provides necessary explanations so readers can understand what’s happening.

validate a date in php

Let’s start without any further ado.

Validate a Date with checkdate() function in PHP

PHP checkdate() is one of the useful functions in the Date/Time category to validate a date in PHP. It checks a Gregorian date’s validity based on the three arguments – month, day, and year. It returns false if any of the three arguments is invalid. Let’s see this function in action in the following example.

echo checkdate(9, 9, 2022) ? "9-9-2022 is a valid date" : "9-9-2022 is an invalid date";
 
echo checkdate(9, 31, 2022) ? "31-9-2022 is a valid date" : "31-9-2022 is an invalid date";
 
//Output
//9-9-2022 is a valid date
//31-9-2022 is an invalid date

The function is able to recognize an invalid date 31-09-2022 (September has 30 days). While this function can check dates in PHP, date formats are sometimes also necessary. So, we need a solution that verifies a date and cares about the right format. Let’s see such a solution in the coming example.

Validate a Date with DateTime Methods in PHP

The example uses a couple of methods from the DateTime class to check if a date and its format are valid. Let’s see the example and then break down the logic to understand it.

function validateDateWithFormat($date, $format = 'd-m-Y')
{
   $d = DateTime::createFromFormat($format, $date);
   $errors = DateTime::getLastErrors();
 
   return $d && empty($errors['warning_count']) && $d->format($format) == $date;
      
}
 
$first_date = "09-09-2022"; //Expect true beacuse the date and the format is correct.
a
$second_date = "09/09/2022"; //Expect false beacuse the date is correct but the format is incorrect.
 
$third_date = "31-09-2022"; //Expect false beacuse the format is correct but the date is incorrect.
 
echo validateDateWithFormat($first_date) ? "{$first_date} is correct" : "{$first_date} is incorrect";
echo validateDateWithFormat($second_date) ? "{$second_date} is correct" : "{$second_date} is incorrect";
echo validateDateWithFormat($third_date) ? "{$third_date} is correct" : "{$third_date} is incorrect";
 
/*
OUTPUT
09-09-2022 is correct
09/09/2022 is incorrect
31-09-2022 is incorrect
*/

The function validateDateWithFormat() uses DateTime’s createFromFormat() and getLastErrors(). Both these functions help cover different edge cases. Let’s debunk the boolean statement.

 return $d && empty($errors['warning_count']) && $d->format($format) == $date;

The variable $d is the return value from createFromFormat(). This function returns false for invalid dates like “33/33/33” but neglects invalid dates like “31/09/2022” and adds offset to make corrections, but it does issue a warning.

The getLastErrors() returns an array that keeps track of the count of errors or warnings if any. So, empty($errors['warning_count']) basically, falsify the statement in case of any warnings.

The final statement $d->format($format) == $date verifies if the date format matches what we expect it to be, defaults to “d-m-Y,” though changeable. 

These three statements decide the return value and return true if a date and format are valid. 

Validate Date and Time Formats in PHP

The example above also works well for time information too. So, you can level down to minutes or even seconds, and the function would be able to validate the date/time and its format. Let’s revisit the last example.

$date_time = date("d-m-Y h:i:s A"); 

echo validateDateWithFormat($date_time, 'd-m-Y h:i:s A') ? "{$date_time} is correct" : "{$date_time} is incorrect";
 
/*
OUTPUT
10-09-2022 07:24:21 PM is correct
*/

How to Validate Time is AM/PM?

The function above can catch invalid time, but what if you want to check if the time is AM/PM? Suppose it is 7:00 PM, and you pass 7:00 AM. How can PHP validate that?

One way to go about the problem is by comparing it with the current hour of the day. Let’s have a look at that.

function checkHour($time, $format = "h A") 
{
    $t = DateTime::createFromFormat($format, $time);
    $now = new DateTime("now");
    return $t && $t->format($format) == $now->format($format);
}

$time = "09:34 AM"; //Its 9:34 PM at the moment. So expect a false;

echo checkHour($time) ? "{$time} is correct" : "{$time} is incorrect";
    
//Output
//09:34 AM is incorrect

The function uses somewhat similar logic, but the main functionality is that it compares the hour and “AM/PM” to the time argument and checks if it is the right hour of the day.

Cool! Let’s stretch a little more and see the validity of time zones.

How to Validate Timezone in PHP?

PHP DateTimeZone features listIdentifiers() that returns a string array of valid timezones. We can check the validity of a timezone by searching it through that array. Here’s how.

$timezones = DateTimeZone::listIdentifiers(); //List of all valid timezones.

echo in_array("Europe/Kyiv", $timezones) ? "Europe/Kyiv is a valid timezone" : "Europe/Kyiv is an invalid timezone";

echo in_array("Wakanda/Wakanda", $timezones) ? "Wakanda/Wakanda is a valid timezone" : "Wakanda/Wakanda is an invalid timezone";

/*
OUTPUT
Europe/Kyiv is an invalid timezone
Wakanda/Wakanda is an invalid timezone
*/

A UNIX timestamp – number of seconds from January 1 1970 00:00:00 UTC. What if we want to check for valid timestamps and weed out invalid timestamp strings? Let’s check that out.

How to Validate Unix Timestamp?

To validate a Unix timestamp, we need to check if the string is numeric, and to do that, we can use ctype_digit. This function expects a string argument and returns true if all the characters are numbers.

$valid_timestamp = (string) strtotime("now");
$invalid_timestamp = "12131e11";

echo ctype_digit($valid_timestamp) ? "{$valid_timestamp} is a valid timestamp" : "{$valid_timestamp} is an invalid timestamp";
echo ctype_digit($invalid_timestamp) ? "{$invalid_timestamp} is a valid timestamp" : "{$invalid_timestamp} is an invalid timestamp";

/*
Output
1662842881 is a valid timestamp
12131e11 is an invalid timestamp
*/

Great! I guess we are good to go. Let’s wrap up.

Conclusion

Wrap Up

This article explores how to validate a date in PHP. It features a couple of options where the first example uses checkdate() to verify the date, and the second uses DateTime methods to check both the valid dates and formats.

Hope you’ve enjoyed this article. Stay tuned for more at FuelingPHP.

Classes and Functions Mentioned

checkdate – (PHP 4, PHP 5, PHP 7, PHP 8) The checkdate function validates Gregorian dates. It is under the Date/Time functions category and has been available from the fourth PHP  installation.

DateTime: (PHP 5 >= 5.2.0, PHP 7, PHP 8) The DateTime class in PHP represents dates/times and features many useful functions to manipulate the objects easily. It was included in PHP 5.2.0 and remained in use. Given its utility and stability, depreciation seems unlikely.

DateTimeZone: (PHP 5 >= 5.2.0, PHP 7, PHP 8) The DateTimeZone class in PHP represents a time zone. It has been included in PHP from the fifth version and is available in the latest PHP version. The class seems stable and reliable, and the probability of depreciation seems low.

ctype_digit: (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) This function validates numeric strings. It has been available from PHP 4.0.4 and has remained stable since.

  Was this information helpful?

Can Your Career Use a Boost?

Check out our free PHP developer career guide. We created this guide as a resource to help fellow programmers level up their careers. This is an excellent resource whether you are new to programming or have been a professional for more than 15 years.

Click here to read the guide


Article Categories

Article Tags

© 2022 Confident.Systems