How to Validate Date String in PHP
Before taking any action with date input, it always a great idea to validate the date string. Date validation helps to check whether the provided string is a valid date format. Using the DateTime class you can easily check if the date string is valid in PHP.
In the example code snippet, we will show you how to validate a date string in PHP. It is very useful for server-side validation of the date input using PHP.
The validateDate() function checks whether the given string is a valid date using PHP. It uses PHP DateTime class to validate date based on the specified format. This function returns TRUE if date string is valid, otherwise FALSE.
- $date – Required. The date string to validate.
- $format – Optional. The format of the date string.
function validateDate($date, $format = 'Y-m-d') $d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
>
Call the validateDate() function and pass the date string in the first parameter.
// Returns false
var_dump(validateDate('2018-14-01'));
var_dump(validateDate('20122-14-01'));
var_dump(validateDate('2018-10-32'));
var_dump(validateDate('2017-5-25'));
// Returns true
var_dump(validateDate('2018-12-01'));
var_dump(validateDate('1970-11-28'));
By default, the format is set to Y-m-d . If you want to allow day and month without leading zeroes, specify the respective format ( Y-n-j ).
// Returns true
var_dump(validateDate('2018-2-5', 'Y-n-j'));
checkdate
Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.
Parameters
The month is between 1 and 12 inclusive.
The day is within the allowed number of days for the given month . Leap year s are taken into consideration.
The year is between 1 and 32767 inclusive.
Return Values
Returns true if the date given is valid; otherwise returns false .
Examples
Example #1 checkdate() example
The above example will output:
See Also
- mktime() — Get Unix timestamp for a date
- strtotime() — Parse about any English textual datetime description into a Unix timestamp
User Contributed Notes 1 note
With DateTime you can make the shortest date&time validator for all formats.
function validateDate ( $date , $format = ‘Y-m-d H:i:s’ )
$d = DateTime :: createFromFormat ( $format , $date );
return $d && $d -> format ( $format ) == $date ;
>
var_dump ( validateDate ( ‘2012-02-28 12:12:12’ )); # true
var_dump ( validateDate ( ‘2012-02-30 12:12:12’ )); # false
var_dump ( validateDate ( ‘2012-02-28’ , ‘Y-m-d’ )); # true
var_dump ( validateDate ( ’28/02/2012′ , ‘d/m/Y’ )); # true
var_dump ( validateDate ( ’30/02/2012′ , ‘d/m/Y’ )); # false
var_dump ( validateDate ( ’14:50′ , ‘H:i’ )); # true
var_dump ( validateDate ( ’14:77′ , ‘H:i’ )); # false
var_dump ( validateDate ( 14 , ‘H’ )); # true
var_dump ( validateDate ( ’14’ , ‘H’ )); # true
var_dump ( validateDate ( ‘2012-02-28T12:12:12+02:00’ , ‘Y-m-d\TH:i:sP’ )); # true
# or
var_dump ( validateDate ( ‘2012-02-28T12:12:12+02:00’ , DateTime :: ATOM )); # true
var_dump ( validateDate ( ‘Tue, 28 Feb 2012 12:12:12 +0200’ , ‘D, d M Y H:i:s O’ )); # true
# or
var_dump ( validateDate ( ‘Tue, 28 Feb 2012 12:12:12 +0200’ , DateTime :: RSS )); # true
var_dump ( validateDate ( ‘Tue, 27 Feb 2012 12:12:12 +0200’ , DateTime :: RSS )); # false
# .
- Date/Time Functions
- checkdate
- date_add
- date_create_from_format
- date_create_immutable_from_format
- date_create_immutable
- date_create
- date_date_set
- date_default_timezone_get
- date_default_timezone_set
- date_diff
- date_format
- date_get_last_errors
- date_interval_create_from_date_string
- date_interval_format
- date_isodate_set
- date_modify
- date_offset_get
- date_parse_from_format
- date_parse
- date_sub
- date_sun_info
- date_sunrise
- date_sunset
- date_time_set
- date_timestamp_get
- date_timestamp_set
- date_timezone_get
- date_timezone_set
- date
- getdate
- gettimeofday
- gmdate
- gmmktime
- gmstrftime
- idate
- localtime
- microtime
- mktime
- strftime
- strptime
- strtotime
- time
- timezone_abbreviations_list
- timezone_identifiers_list
- timezone_location_get
- timezone_name_from_abbr
- timezone_name_get
- timezone_offset_get
- timezone_open
- timezone_transitions_get
- timezone_version_get
How to Check Valid Date Format in PHP?
New here? Like SchoolsOfWeb on Facebook to stay up to date with new posts.
Problem:
Perhaps user entered date in the form and now, you want to check if it is in right date format before further processing the data or inserting it into the database.
Solution:
There are few ways to verify a valid date format. We’ll investigate two of those below-
Method 1: Using date_parse() function
If you pass a valid date format to the function date_parse(), it will return an associative array containing detail about the date like day, month, year etc. Alone with those info, the function also returns warning and error numbers as warning_count and error_count keys respectively in the array if the supplied date is not a valid date format .
Output:
It is not a valid date.Please note that date_parse() function accepts those date formats that are accepted by strtotime() function. See the list of supported date and time formats. So, if you use these formats, the date_parse() function will return true.
Method 2: Using DateTime class
PHP provides an excellent wealth of ready made classes to help you developers solve common problems. To solve the date & time issues, PHP provides DateTime class.
There are 2 steps to check a valid date format using DateTime class-
- Create a new DateTIme object using createFromFormat() method which allows you to create a DateTIme object according to the format you specified in its parameters.
- Then, use getLastErrors() method to check if there is any error or warning in the object you just created.
In the following example, we’ll check whether 2014-04-31 is a valid date. Note: April has 30 days. So, it is not a valid date.
getLastErrors(); if($err['warning_count'] == 0 && $err['error_count'] == 0) echo "It's a valid date"; else echo "It's not a valid date"; ?>
Output:
It’s not a valid dateLine 2 Here, we create a DateTime object($date) using createFromFormat() method with our supplied date(‘2014-04-31’). The second parameter is our supplied date and the first one is the representation of character formatting of our supplied date. To see the list of other formatting character, check formatting character list . Line 3 If the DateTime object($date) we created in the previous line has any error or warning, we can get to know it by using getLastErrors() method. This method returns an array with all errors and warnings. We name that array as $err. Line 4 The number of errors and warnings are stored in the error_count and warning_count keys respectively in the array. Here, we check if any error or warning exists. If it has no warning or errors, then we print “It’s a valid date” otherwise, “It’s not a valid date”. As the date has warning, it will display the next message. You may have different date format. In that case, match the formatting characters in the first arguments in createFromFormat() method with your supplied date in the second parameter. Ex.
How to Validate Date String in PHP
Before taking any action with date input, it always a great idea to validate the date string. Date validation helps to check whether the provided string is a valid date format. Using the DateTime class you can easily check if the date string is valid in PHP.
In the example code snippet, we will show you how to validate a date string in PHP. It is very useful for server-side validation of the date input using PHP.
The validateDate() function checks whether the given string is a valid date using PHP. It uses PHP DateTime class to validate date based on the specified format. This function returns TRUE if date string is valid, otherwise FALSE.
- $date – Required. The date string to validate.
- $format – Optional. The format of the date string.
function validateDate($date, $format = 'Y-m-d') $d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
>Call the validateDate() function and pass the date string in the first parameter.
// Returns false
var_dump(validateDate('2018-14-01'));
var_dump(validateDate('20122-14-01'));
var_dump(validateDate('2018-10-32'));
var_dump(validateDate('2017-5-25'));
// Returns true
var_dump(validateDate('2018-12-01'));
var_dump(validateDate('1970-11-28'));By default, the format is set to Y-m-d . If you want to allow day and month without leading zeroes, specify the respective format ( Y-n-j ).
// Returns true
var_dump(validateDate('2018-2-5', 'Y-n-j'));