- checkdate
- Parameters
- Return Values
- Examples
- See Also
- checkdate
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 1 note
- How To Validate Date in PHP
- Date Validation by Using checkdate() Function
- Syntax:
- Example 1: Check the Validity of Different Types of Date
- Example 2: Print Message Based on the Output of checkdate() Function
- Example 3: Check the Validity of the Date Taken From the User
- Date Validation Using createFromFormat() Function
- Syntax:
- Example 4: Check Date Validity by Using createFromFormat() and format() Functions
- Example 5: Check Date Validity by Using createFromFormat() and getLastErrors() Functions
- Conclusion
- About the author
- Fahmida Yesmin
- How to Validate Date String in PHP
checkdate
Проверяет достоверность даты,сформированной аргументами.Дата считается действительной,если каждый параметр правильно определен.
Parameters
Месяц-от 1 до 12 включительно.
День находится в пределах разрешенного количества дней для данного month . Прыжок year s принимается во внимание.
Год находится между 1 и 32767 включительно.
Return Values
Возвращает true если указанная дата действительна; в противном случае возвращает false .
Examples
Пример # 1 checkdate () Пример
var_dump(checkdate(12, 31, 2000)); var_dump(checkdate(2, 29, 2001)); ?>
Выводится приведенный выше пример:
See Also
- mktime () — Получить временную метку Unix для даты
- strtotime () — Преобразует любое текстовое описание даты и времени на английском языке в метку времени Unix
PHP 8.2
(PHP 4,5,7,8)ceil Округление дробей в большую сторону Возвращает следующее наибольшее целое значение,при необходимости округляя num в большую сторону.
(PHP 4, 5, 7, 8) chdir Изменить каталог Изменяет текущий каталог PHP Новый текущий каталог Возвращает true в случае успеха или false в случае неудачи.
(PHP 4,5,7,8)checkdnsrr записи,соответствующие заданному IP-адресу имени хоста в Интернете Ищет в DNS записи типа,соответствующего имени хоста.
(PHP 4,5,7,8)chgrp Изменить группу файла Попытка изменить группу файла filename Только суперпользователь может произвольно изменять группу файла;остальные
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 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:
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.
/*Check the validity of different types of date values */
//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:
//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.
//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.
‘ ;
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 )
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.
//Assign a date value as a string
//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.
//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.
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'));