Date Regular Expression Not Returning True - php

For some reason this is always returning false... when entering "2014 12 12" into the form. It is this format to enter into a database.
$date = trim($_POST['date']);
in my library.php i have :
function validateDate($date) {
if(preg_match('/^[0-9]{2,4}[\-[[:space:]]]{1}[0-9]{1,2}[\-[[:space:]]]{1}[0-9]{1,2}$/',$date)){
return true;
}
else{
return false;
}
}
and in my php i have :
if (validateDate($date)){
$dateCSS = 'style="border-color: #98faad;"';
}
else {
$dateCSS = 'style="border-color: red;"';
$flag = false;
}

Try this regexp:
^[0-9]{2,4}[\-[:space:]]{1}[0-9]{1,2}[\-[:space:]]{1}[0-9]{1,2}$

A more reliable way to validate a date is to use the datetime extension.
function validateDate($date, $format = 'Y d m') {
return \DateTime::createFromFormat($format, $date) !== false;
}
This way you do not have to resort to using regular expressions, and you will be able to actually validate dates correctly (for example, something like 2014 12 51 will not validate).
if ( ! validateDate('2014 12 51')) {
echo 'Not valid!';
}
It will also allow you to validate more complicated dates, if you will be required to do that some day:
if (validateDate('16th September 2014', 'dS F Y')) {
echo 'Valid!';
}
For the $format argument you must use the formatting options that DateTime::createFromFormat() accepts.

Related

PHP DateTime::createFromFormat check issue [duplicate]

I'm receiving a date string from an API, and it is formatted as yyyy-mm-dd.
I am currently using a regex to validate the string format, which works ok, but I can see some cases where it could be a correct format according to the string but actually an invalid date. i.e. 2013-13-01, for example.
Is there a better way in PHP to take a string such as 2013-13-01 and tell if it is a valid date or not for the format yyyy-mm-dd?
You can use DateTime::createFromFormat() for this purpose:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
return $d && $d->format($format) === $date;
}
[Function taken from this answer. Also on php.net. Originally written by Glavić.]
Test cases:
var_dump(validateDate('2013-13-01')); // false
var_dump(validateDate('20132-13-01')); // false
var_dump(validateDate('2013-11-32')); // false
var_dump(validateDate('2012-2-25')); // false
var_dump(validateDate('2013-12-01')); // true
var_dump(validateDate('1970-12-01')); // true
var_dump(validateDate('2012-02-29')); // true
var_dump(validateDate('2012', 'Y')); // true
var_dump(validateDate('12012', 'Y')); // false
Demo!
Determine if any string is a date
function checkIsAValidDate($myDateString){
return (bool)strtotime($myDateString);
}
Use in simple way with php prebuilt function:
function checkmydate($date) {
$tempDate = explode('-', $date);
// checkdate(month, day, year)
return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}
Test
checkmydate('2015-12-01'); //true
checkmydate('2015-14-04'); //false
Determine if string is a date, even if string is a non-standard format
(strtotime doesn't accept any custom format)
<?php
function validateDateTime($dateStr, $format)
{
date_default_timezone_set('UTC');
$date = DateTime::createFromFormat($format, $dateStr);
return $date && ($date->format($format) === $dateStr);
}
// These return true
validateDateTime('2001-03-10 17:16:18', 'Y-m-d H:i:s');
validateDateTime('2001-03-10', 'Y-m-d');
validateDateTime('2001', 'Y');
validateDateTime('Mon', 'D');
validateDateTime('March 10, 2001, 5:16 pm', 'F j, Y, g:i a');
validateDateTime('March 10, 2001, 5:16 pm', 'F j, Y, g:i a');
validateDateTime('03.10.01', 'm.d.y');
validateDateTime('10, 3, 2001', 'j, n, Y');
validateDateTime('20010310', 'Ymd');
validateDateTime('05-16-18, 10-03-01', 'h-i-s, j-m-y');
validateDateTime('Monday 8th of August 2005 03:12:46 PM', 'l jS \of F Y h:i:s A');
validateDateTime('Wed, 25 Sep 2013 15:28:57', 'D, d M Y H:i:s');
validateDateTime('17:03:18 is the time', 'H:m:s \i\s \t\h\e \t\i\m\e');
validateDateTime('17:16:18', 'H:i:s');
// These return false
validateDateTime('2001-03-10 17:16:18', 'Y-m-D H:i:s');
validateDateTime('2001', 'm');
validateDateTime('Mon', 'D-m-y');
validateDateTime('Mon', 'D-m-y');
validateDateTime('2001-13-04', 'Y-m-d');
This option is not only simple but also accepts almost any format, although with non-standard formats it can be buggy.
$timestamp = strtotime($date);
return $timestamp ? $date : null;
The easiest way to check if given date is valid probably converting it to unixtime using strtotime, formatting it to the given date's format, then comparing it:
function isValidDate($date) {
return date('Y-m-d', strtotime($date)) === $date;
}
Of course you can use regular expression to check for validness, but it will be limited to given format, every time you will have to edit it to satisfy another formats, and also it will be more than required. Built-in functions is the best way (in most cases) to achieve jobs.
You can also Parse the date for month date and year and then you can use the PHP function checkdate() which you can read about here: http://php.net/manual/en/function.checkdate.php
You can also try this one:
$date="2013-13-01";
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date))
{
echo 'Date is valid';
}else{
echo 'Date is invalid';
}
I'm afraid that most voted solution (https://stackoverflow.com/a/19271434/3283279) is not working properly. The fourth test case (var_dump(validateDate('2012-2-25')); // false) is wrong. The date is correct, because it corresponds to the format - the m allows a month with or without leading zero (see: http://php.net/manual/en/datetime.createfromformat.php). Therefore a date 2012-2-25 is in format Y-m-d and the test case must be true not false.
I believe that better solution is to test possible error as follows:
function validateDate($date, $format = 'Y-m-d') {
DateTime::createFromFormat($format, $date);
$errors = DateTime::getLastErrors();
return $errors['warning_count'] === 0 && $errors['error_count'] === 0;
}
Accordling with cl-sah's answer, but this sound better, shorter...
function checkmydate($date) {
$tempDate = explode('-', $date);
return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}
Test
checkmydate('2015-12-01');//true
checkmydate('2015-14-04');//false
I have this thing that, even with PHP, I like to find functional solutions. So, for example, the answer given by #migli is really a good one, highly flexible and elegant.
But it has a problem: what if you need to validate a lot of DateTime strings with the same format? You would have to repeat the format all over the place, what goes against the DRY principle. We could put the format in a constant, but still, we would have to pass the constant as an argument to every function call.
But fear no more! We can use currying to our rescue! PHP doesn't make this task pleasant, but it's still possible to implement currying with PHP:
<?php
function validateDateTime($format)
{
return function($dateStr) use ($format) {
$date = DateTime::createFromFormat($format, $dateStr);
return $date && $date->format($format) === $dateStr;
};
}
So, what we just did? Basically we wrapped the function body in an anonymous and returned such function instead. We can call the validation function like this:
validateDateTime('Y-m-d H:i:s')('2017-02-06 17:07:11'); // true
Yeah, not a big difference... but the real power comes from the partially applied function, made possible by currying:
// Get a partially applied function
$validate = validateDateTime('Y-m-d H:i:s');
// Now you can use it everywhere, without repeating the format!
$validate('2017-02-06 17:09:31'); // true
$validate('1999-03-31 07:07:07'); // true
$validate('13-2-4 3:2:45'); // false
Functional programming FTW!
How about this one?
We simply use a try-catch block.
$dateTime = 'an invalid datetime';
try {
$dateTimeObject = new DateTime($dateTime);
} catch (Exception $exc) {
echo 'Do something with an invalid DateTime';
}
This approach is not limited to only one date/time format, and you don't need to define any function.
Validate with checkdate function:
$date = '2019-02-30';
$date_parts = explode( '-', $date );
if(checkdate( $date_parts[1], $date_parts[2], $date_parts[0] )){
//date is valid
}else{
//date is invalid
}
Tested Regex solution:
function isValidDate($date)
{
if (preg_match("/^(((((1[26]|2[048])00)|[12]\d([2468][048]|[13579][26]|0[48]))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|[12]\d))))|((([12]\d([02468][1235679]|[13579][01345789]))|((1[1345789]|2[1235679])00))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|1\d|2[0-8])))))$/", $date)) {
return $date;
}
return null;
}
This will return null if the date is invalid or is not yyyy-mm-dd format, otherwise it will return the date.
/*********************************************************************************
Returns TRUE if the input parameter is a valid date string in "YYYY-MM-DD" format (aka "MySQL date format")
The date separator can be only the '-' character.
*********************************************************************************/
function isMysqlDate($yyyymmdd)
{
return checkdate(substr($yyyymmdd, 5, 2), substr($yyyymmdd, 8), substr($yyyymmdd, 0, 4))
&& (substr($yyyymmdd, 4, 1) === '-')
&& (substr($yyyymmdd, 7, 1) === '-');
}
To add onto the accepted answer, you can further check for a valid date or DateTime by checking if the formatted date is an instanceof DateTime.
$date = DateTime::createFromFormat('Ymd', $value);
$is_datetime = ($date instanceof DateTime);
$is_valid_datetime_format = $is_datetime
? ($date->format('Ymd') === $value)
: false;
if (!$is_datetime || !$is_valid_datetime_format) {
// Not a valid date.
return false;
}
This will catch any values that are not a DateTime such as random strings or an invalid date such as 20202020.
/**** date check is a recursive function. it's need 3 argument
MONTH,DAY,YEAR. ******/
$always_valid_date = $this->date_check($month,$day,$year);
private function date_check($month,$day,$year){
/** checkdate() is a php function that check a date is valid
or not. if valid date it's return true else false. **/
$status = checkdate($month,$day,$year);
if($status == true){
$always_valid_date = $year . '-' . $month . '-' . $day;
return $always_valid_date;
}else{
$day = ($day - 1);
/**recursive call**/
return $this->date_check($month,$day,$year);
}
}
Try and let me know it works for me
$date = \DateTime::createFromFormat('d/m/Y', $dataRowValue);
if (!empty($date)) {
//Your logic
}else{
//Error
}
if you pass any alpha or alphanumberic values it will give you the empty value in return
Regex solution
function verify_date($date){
/* correct format = "2012-09-15 11:23:32" or "2012-09-15"*/
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])( (0[0-9]|[1-2][0-4]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]))?$/",$date)) {
return true;
} else {
die("Wrong date format: it should be '2012-09-15 11:23:32' or '2012-09-15', date received is: ".$date);
}
}
Try this:
$myday = '2022-1-30';
if (($timestamp = strtotime($myday)) === false) {
echo 'The string ('.$myday.') is not date';
} else {
echo 'The string ('.$myday.') is date = ' . date('l dS \o\f F Y h:i:s A', $timestamp);
}
Give this a try:
$date = "2017-10-01";
function date_checker($input,$devider){
$output = false;
$input = explode($devider, $input);
$year = $input[0];
$month = $input[1];
$day = $input[2];
if (is_numeric($year) && is_numeric($month) && is_numeric($day)) {
if (strlen($year) == 4 && strlen($month) == 2 && strlen($day) == 2) {
$output = true;
}
}
return $output;
}
if (date_checker($date, '-')) {
echo "The function is working";
}else {
echo "The function isNOT working";
}

How do i vallidate date in Y-m-d format and check each value is valid if any character occurred in PHP? [duplicate]

I'm receiving a date string from an API, and it is formatted as yyyy-mm-dd.
I am currently using a regex to validate the string format, which works ok, but I can see some cases where it could be a correct format according to the string but actually an invalid date. i.e. 2013-13-01, for example.
Is there a better way in PHP to take a string such as 2013-13-01 and tell if it is a valid date or not for the format yyyy-mm-dd?
You can use DateTime::createFromFormat() for this purpose:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
return $d && $d->format($format) === $date;
}
[Function taken from this answer. Also on php.net. Originally written by Glavić.]
Test cases:
var_dump(validateDate('2013-13-01')); // false
var_dump(validateDate('20132-13-01')); // false
var_dump(validateDate('2013-11-32')); // false
var_dump(validateDate('2012-2-25')); // false
var_dump(validateDate('2013-12-01')); // true
var_dump(validateDate('1970-12-01')); // true
var_dump(validateDate('2012-02-29')); // true
var_dump(validateDate('2012', 'Y')); // true
var_dump(validateDate('12012', 'Y')); // false
Demo!
Determine if any string is a date
function checkIsAValidDate($myDateString){
return (bool)strtotime($myDateString);
}
Use in simple way with php prebuilt function:
function checkmydate($date) {
$tempDate = explode('-', $date);
// checkdate(month, day, year)
return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}
Test
checkmydate('2015-12-01'); //true
checkmydate('2015-14-04'); //false
Determine if string is a date, even if string is a non-standard format
(strtotime doesn't accept any custom format)
<?php
function validateDateTime($dateStr, $format)
{
date_default_timezone_set('UTC');
$date = DateTime::createFromFormat($format, $dateStr);
return $date && ($date->format($format) === $dateStr);
}
// These return true
validateDateTime('2001-03-10 17:16:18', 'Y-m-d H:i:s');
validateDateTime('2001-03-10', 'Y-m-d');
validateDateTime('2001', 'Y');
validateDateTime('Mon', 'D');
validateDateTime('March 10, 2001, 5:16 pm', 'F j, Y, g:i a');
validateDateTime('March 10, 2001, 5:16 pm', 'F j, Y, g:i a');
validateDateTime('03.10.01', 'm.d.y');
validateDateTime('10, 3, 2001', 'j, n, Y');
validateDateTime('20010310', 'Ymd');
validateDateTime('05-16-18, 10-03-01', 'h-i-s, j-m-y');
validateDateTime('Monday 8th of August 2005 03:12:46 PM', 'l jS \of F Y h:i:s A');
validateDateTime('Wed, 25 Sep 2013 15:28:57', 'D, d M Y H:i:s');
validateDateTime('17:03:18 is the time', 'H:m:s \i\s \t\h\e \t\i\m\e');
validateDateTime('17:16:18', 'H:i:s');
// These return false
validateDateTime('2001-03-10 17:16:18', 'Y-m-D H:i:s');
validateDateTime('2001', 'm');
validateDateTime('Mon', 'D-m-y');
validateDateTime('Mon', 'D-m-y');
validateDateTime('2001-13-04', 'Y-m-d');
This option is not only simple but also accepts almost any format, although with non-standard formats it can be buggy.
$timestamp = strtotime($date);
return $timestamp ? $date : null;
The easiest way to check if given date is valid probably converting it to unixtime using strtotime, formatting it to the given date's format, then comparing it:
function isValidDate($date) {
return date('Y-m-d', strtotime($date)) === $date;
}
Of course you can use regular expression to check for validness, but it will be limited to given format, every time you will have to edit it to satisfy another formats, and also it will be more than required. Built-in functions is the best way (in most cases) to achieve jobs.
You can also Parse the date for month date and year and then you can use the PHP function checkdate() which you can read about here: http://php.net/manual/en/function.checkdate.php
You can also try this one:
$date="2013-13-01";
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date))
{
echo 'Date is valid';
}else{
echo 'Date is invalid';
}
I'm afraid that most voted solution (https://stackoverflow.com/a/19271434/3283279) is not working properly. The fourth test case (var_dump(validateDate('2012-2-25')); // false) is wrong. The date is correct, because it corresponds to the format - the m allows a month with or without leading zero (see: http://php.net/manual/en/datetime.createfromformat.php). Therefore a date 2012-2-25 is in format Y-m-d and the test case must be true not false.
I believe that better solution is to test possible error as follows:
function validateDate($date, $format = 'Y-m-d') {
DateTime::createFromFormat($format, $date);
$errors = DateTime::getLastErrors();
return $errors['warning_count'] === 0 && $errors['error_count'] === 0;
}
Accordling with cl-sah's answer, but this sound better, shorter...
function checkmydate($date) {
$tempDate = explode('-', $date);
return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}
Test
checkmydate('2015-12-01');//true
checkmydate('2015-14-04');//false
I have this thing that, even with PHP, I like to find functional solutions. So, for example, the answer given by #migli is really a good one, highly flexible and elegant.
But it has a problem: what if you need to validate a lot of DateTime strings with the same format? You would have to repeat the format all over the place, what goes against the DRY principle. We could put the format in a constant, but still, we would have to pass the constant as an argument to every function call.
But fear no more! We can use currying to our rescue! PHP doesn't make this task pleasant, but it's still possible to implement currying with PHP:
<?php
function validateDateTime($format)
{
return function($dateStr) use ($format) {
$date = DateTime::createFromFormat($format, $dateStr);
return $date && $date->format($format) === $dateStr;
};
}
So, what we just did? Basically we wrapped the function body in an anonymous and returned such function instead. We can call the validation function like this:
validateDateTime('Y-m-d H:i:s')('2017-02-06 17:07:11'); // true
Yeah, not a big difference... but the real power comes from the partially applied function, made possible by currying:
// Get a partially applied function
$validate = validateDateTime('Y-m-d H:i:s');
// Now you can use it everywhere, without repeating the format!
$validate('2017-02-06 17:09:31'); // true
$validate('1999-03-31 07:07:07'); // true
$validate('13-2-4 3:2:45'); // false
Functional programming FTW!
How about this one?
We simply use a try-catch block.
$dateTime = 'an invalid datetime';
try {
$dateTimeObject = new DateTime($dateTime);
} catch (Exception $exc) {
echo 'Do something with an invalid DateTime';
}
This approach is not limited to only one date/time format, and you don't need to define any function.
Validate with checkdate function:
$date = '2019-02-30';
$date_parts = explode( '-', $date );
if(checkdate( $date_parts[1], $date_parts[2], $date_parts[0] )){
//date is valid
}else{
//date is invalid
}
Tested Regex solution:
function isValidDate($date)
{
if (preg_match("/^(((((1[26]|2[048])00)|[12]\d([2468][048]|[13579][26]|0[48]))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|[12]\d))))|((([12]\d([02468][1235679]|[13579][01345789]))|((1[1345789]|2[1235679])00))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|1\d|2[0-8])))))$/", $date)) {
return $date;
}
return null;
}
This will return null if the date is invalid or is not yyyy-mm-dd format, otherwise it will return the date.
/*********************************************************************************
Returns TRUE if the input parameter is a valid date string in "YYYY-MM-DD" format (aka "MySQL date format")
The date separator can be only the '-' character.
*********************************************************************************/
function isMysqlDate($yyyymmdd)
{
return checkdate(substr($yyyymmdd, 5, 2), substr($yyyymmdd, 8), substr($yyyymmdd, 0, 4))
&& (substr($yyyymmdd, 4, 1) === '-')
&& (substr($yyyymmdd, 7, 1) === '-');
}
To add onto the accepted answer, you can further check for a valid date or DateTime by checking if the formatted date is an instanceof DateTime.
$date = DateTime::createFromFormat('Ymd', $value);
$is_datetime = ($date instanceof DateTime);
$is_valid_datetime_format = $is_datetime
? ($date->format('Ymd') === $value)
: false;
if (!$is_datetime || !$is_valid_datetime_format) {
// Not a valid date.
return false;
}
This will catch any values that are not a DateTime such as random strings or an invalid date such as 20202020.
/**** date check is a recursive function. it's need 3 argument
MONTH,DAY,YEAR. ******/
$always_valid_date = $this->date_check($month,$day,$year);
private function date_check($month,$day,$year){
/** checkdate() is a php function that check a date is valid
or not. if valid date it's return true else false. **/
$status = checkdate($month,$day,$year);
if($status == true){
$always_valid_date = $year . '-' . $month . '-' . $day;
return $always_valid_date;
}else{
$day = ($day - 1);
/**recursive call**/
return $this->date_check($month,$day,$year);
}
}
Try and let me know it works for me
$date = \DateTime::createFromFormat('d/m/Y', $dataRowValue);
if (!empty($date)) {
//Your logic
}else{
//Error
}
if you pass any alpha or alphanumberic values it will give you the empty value in return
Regex solution
function verify_date($date){
/* correct format = "2012-09-15 11:23:32" or "2012-09-15"*/
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])( (0[0-9]|[1-2][0-4]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]))?$/",$date)) {
return true;
} else {
die("Wrong date format: it should be '2012-09-15 11:23:32' or '2012-09-15', date received is: ".$date);
}
}
Try this:
$myday = '2022-1-30';
if (($timestamp = strtotime($myday)) === false) {
echo 'The string ('.$myday.') is not date';
} else {
echo 'The string ('.$myday.') is date = ' . date('l dS \o\f F Y h:i:s A', $timestamp);
}
Give this a try:
$date = "2017-10-01";
function date_checker($input,$devider){
$output = false;
$input = explode($devider, $input);
$year = $input[0];
$month = $input[1];
$day = $input[2];
if (is_numeric($year) && is_numeric($month) && is_numeric($day)) {
if (strlen($year) == 4 && strlen($month) == 2 && strlen($day) == 2) {
$output = true;
}
}
return $output;
}
if (date_checker($date, '-')) {
echo "The function is working";
}else {
echo "The function isNOT working";
}

Validation Error dates PHP

I'm trying to validate dates in PHP, but the problem is that with some dates work, an example would be: "02/2/2015" returns true, "20/12/2015" false returns, is a serious problem and I see no error in the code.
Function.
<?php
function check_date($date) {
$open_date = explode('/', $date);
if (count($open_date) == 3) {
if (checkdate($open_date[0], $open_date[1], $open_date[2])) {
return true;
} else {
return false;
}
} else {
return false;
}
}
//$date = "02/2/2015"; // return true !
$date = "20/12/2015"; // return false ?
if(check_date($date)) {
echo "valid";
} else {
echo "invalid";
}
?>
How could solve this problem?
checkdate expects a month, day and year, in that order:
https://secure.php.net/manual/en/function.checkdate.php
If your dates are formatted as day/month/year then you can still use checkdate, you'll just have to change the order of the parameters:
if (checkdate($open_date[1], $open_date[0], $open_date[2]))
The signature of checkdate function looks like checkdate(month,day,year); . You can have upto 12 months and not 20. :-)

Correctly determine if date string is a valid date in that format

I'm receiving a date string from an API, and it is formatted as yyyy-mm-dd.
I am currently using a regex to validate the string format, which works ok, but I can see some cases where it could be a correct format according to the string but actually an invalid date. i.e. 2013-13-01, for example.
Is there a better way in PHP to take a string such as 2013-13-01 and tell if it is a valid date or not for the format yyyy-mm-dd?
You can use DateTime::createFromFormat() for this purpose:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
return $d && $d->format($format) === $date;
}
[Function taken from this answer. Also on php.net. Originally written by Glavić.]
Test cases:
var_dump(validateDate('2013-13-01')); // false
var_dump(validateDate('20132-13-01')); // false
var_dump(validateDate('2013-11-32')); // false
var_dump(validateDate('2012-2-25')); // false
var_dump(validateDate('2013-12-01')); // true
var_dump(validateDate('1970-12-01')); // true
var_dump(validateDate('2012-02-29')); // true
var_dump(validateDate('2012', 'Y')); // true
var_dump(validateDate('12012', 'Y')); // false
Demo!
Determine if any string is a date
function checkIsAValidDate($myDateString){
return (bool)strtotime($myDateString);
}
Use in simple way with php prebuilt function:
function checkmydate($date) {
$tempDate = explode('-', $date);
// checkdate(month, day, year)
return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}
Test
checkmydate('2015-12-01'); //true
checkmydate('2015-14-04'); //false
Determine if string is a date, even if string is a non-standard format
(strtotime doesn't accept any custom format)
<?php
function validateDateTime($dateStr, $format)
{
date_default_timezone_set('UTC');
$date = DateTime::createFromFormat($format, $dateStr);
return $date && ($date->format($format) === $dateStr);
}
// These return true
validateDateTime('2001-03-10 17:16:18', 'Y-m-d H:i:s');
validateDateTime('2001-03-10', 'Y-m-d');
validateDateTime('2001', 'Y');
validateDateTime('Mon', 'D');
validateDateTime('March 10, 2001, 5:16 pm', 'F j, Y, g:i a');
validateDateTime('March 10, 2001, 5:16 pm', 'F j, Y, g:i a');
validateDateTime('03.10.01', 'm.d.y');
validateDateTime('10, 3, 2001', 'j, n, Y');
validateDateTime('20010310', 'Ymd');
validateDateTime('05-16-18, 10-03-01', 'h-i-s, j-m-y');
validateDateTime('Monday 8th of August 2005 03:12:46 PM', 'l jS \of F Y h:i:s A');
validateDateTime('Wed, 25 Sep 2013 15:28:57', 'D, d M Y H:i:s');
validateDateTime('17:03:18 is the time', 'H:m:s \i\s \t\h\e \t\i\m\e');
validateDateTime('17:16:18', 'H:i:s');
// These return false
validateDateTime('2001-03-10 17:16:18', 'Y-m-D H:i:s');
validateDateTime('2001', 'm');
validateDateTime('Mon', 'D-m-y');
validateDateTime('Mon', 'D-m-y');
validateDateTime('2001-13-04', 'Y-m-d');
This option is not only simple but also accepts almost any format, although with non-standard formats it can be buggy.
$timestamp = strtotime($date);
return $timestamp ? $date : null;
The easiest way to check if given date is valid probably converting it to unixtime using strtotime, formatting it to the given date's format, then comparing it:
function isValidDate($date) {
return date('Y-m-d', strtotime($date)) === $date;
}
Of course you can use regular expression to check for validness, but it will be limited to given format, every time you will have to edit it to satisfy another formats, and also it will be more than required. Built-in functions is the best way (in most cases) to achieve jobs.
You can also Parse the date for month date and year and then you can use the PHP function checkdate() which you can read about here: http://php.net/manual/en/function.checkdate.php
You can also try this one:
$date="2013-13-01";
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date))
{
echo 'Date is valid';
}else{
echo 'Date is invalid';
}
I'm afraid that most voted solution (https://stackoverflow.com/a/19271434/3283279) is not working properly. The fourth test case (var_dump(validateDate('2012-2-25')); // false) is wrong. The date is correct, because it corresponds to the format - the m allows a month with or without leading zero (see: http://php.net/manual/en/datetime.createfromformat.php). Therefore a date 2012-2-25 is in format Y-m-d and the test case must be true not false.
I believe that better solution is to test possible error as follows:
function validateDate($date, $format = 'Y-m-d') {
DateTime::createFromFormat($format, $date);
$errors = DateTime::getLastErrors();
return $errors['warning_count'] === 0 && $errors['error_count'] === 0;
}
Accordling with cl-sah's answer, but this sound better, shorter...
function checkmydate($date) {
$tempDate = explode('-', $date);
return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}
Test
checkmydate('2015-12-01');//true
checkmydate('2015-14-04');//false
I have this thing that, even with PHP, I like to find functional solutions. So, for example, the answer given by #migli is really a good one, highly flexible and elegant.
But it has a problem: what if you need to validate a lot of DateTime strings with the same format? You would have to repeat the format all over the place, what goes against the DRY principle. We could put the format in a constant, but still, we would have to pass the constant as an argument to every function call.
But fear no more! We can use currying to our rescue! PHP doesn't make this task pleasant, but it's still possible to implement currying with PHP:
<?php
function validateDateTime($format)
{
return function($dateStr) use ($format) {
$date = DateTime::createFromFormat($format, $dateStr);
return $date && $date->format($format) === $dateStr;
};
}
So, what we just did? Basically we wrapped the function body in an anonymous and returned such function instead. We can call the validation function like this:
validateDateTime('Y-m-d H:i:s')('2017-02-06 17:07:11'); // true
Yeah, not a big difference... but the real power comes from the partially applied function, made possible by currying:
// Get a partially applied function
$validate = validateDateTime('Y-m-d H:i:s');
// Now you can use it everywhere, without repeating the format!
$validate('2017-02-06 17:09:31'); // true
$validate('1999-03-31 07:07:07'); // true
$validate('13-2-4 3:2:45'); // false
Functional programming FTW!
How about this one?
We simply use a try-catch block.
$dateTime = 'an invalid datetime';
try {
$dateTimeObject = new DateTime($dateTime);
} catch (Exception $exc) {
echo 'Do something with an invalid DateTime';
}
This approach is not limited to only one date/time format, and you don't need to define any function.
Validate with checkdate function:
$date = '2019-02-30';
$date_parts = explode( '-', $date );
if(checkdate( $date_parts[1], $date_parts[2], $date_parts[0] )){
//date is valid
}else{
//date is invalid
}
Tested Regex solution:
function isValidDate($date)
{
if (preg_match("/^(((((1[26]|2[048])00)|[12]\d([2468][048]|[13579][26]|0[48]))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|[12]\d))))|((([12]\d([02468][1235679]|[13579][01345789]))|((1[1345789]|2[1235679])00))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|1\d|2[0-8])))))$/", $date)) {
return $date;
}
return null;
}
This will return null if the date is invalid or is not yyyy-mm-dd format, otherwise it will return the date.
/*********************************************************************************
Returns TRUE if the input parameter is a valid date string in "YYYY-MM-DD" format (aka "MySQL date format")
The date separator can be only the '-' character.
*********************************************************************************/
function isMysqlDate($yyyymmdd)
{
return checkdate(substr($yyyymmdd, 5, 2), substr($yyyymmdd, 8), substr($yyyymmdd, 0, 4))
&& (substr($yyyymmdd, 4, 1) === '-')
&& (substr($yyyymmdd, 7, 1) === '-');
}
To add onto the accepted answer, you can further check for a valid date or DateTime by checking if the formatted date is an instanceof DateTime.
$date = DateTime::createFromFormat('Ymd', $value);
$is_datetime = ($date instanceof DateTime);
$is_valid_datetime_format = $is_datetime
? ($date->format('Ymd') === $value)
: false;
if (!$is_datetime || !$is_valid_datetime_format) {
// Not a valid date.
return false;
}
This will catch any values that are not a DateTime such as random strings or an invalid date such as 20202020.
/**** date check is a recursive function. it's need 3 argument
MONTH,DAY,YEAR. ******/
$always_valid_date = $this->date_check($month,$day,$year);
private function date_check($month,$day,$year){
/** checkdate() is a php function that check a date is valid
or not. if valid date it's return true else false. **/
$status = checkdate($month,$day,$year);
if($status == true){
$always_valid_date = $year . '-' . $month . '-' . $day;
return $always_valid_date;
}else{
$day = ($day - 1);
/**recursive call**/
return $this->date_check($month,$day,$year);
}
}
Try and let me know it works for me
$date = \DateTime::createFromFormat('d/m/Y', $dataRowValue);
if (!empty($date)) {
//Your logic
}else{
//Error
}
if you pass any alpha or alphanumberic values it will give you the empty value in return
Regex solution
function verify_date($date){
/* correct format = "2012-09-15 11:23:32" or "2012-09-15"*/
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])( (0[0-9]|[1-2][0-4]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]))?$/",$date)) {
return true;
} else {
die("Wrong date format: it should be '2012-09-15 11:23:32' or '2012-09-15', date received is: ".$date);
}
}
Try this:
$myday = '2022-1-30';
if (($timestamp = strtotime($myday)) === false) {
echo 'The string ('.$myday.') is not date';
} else {
echo 'The string ('.$myday.') is date = ' . date('l dS \o\f F Y h:i:s A', $timestamp);
}
Give this a try:
$date = "2017-10-01";
function date_checker($input,$devider){
$output = false;
$input = explode($devider, $input);
$year = $input[0];
$month = $input[1];
$day = $input[2];
if (is_numeric($year) && is_numeric($month) && is_numeric($day)) {
if (strlen($year) == 4 && strlen($month) == 2 && strlen($day) == 2) {
$output = true;
}
}
return $output;
}
if (date_checker($date, '-')) {
echo "The function is working";
}else {
echo "The function isNOT working";
}

Verify valid date using PHP's DateTime class

Below is how I previously verified dates. I also had my own functions to convert date formats, however, now am using PHP's DateTime class so no longer need them. How should I best verify a valid date using DataTime? Please also let me know whether you think I should be using DataTime in the first place. Thanks
PS. I am using Object oriented style, and not Procedural style.
static public function verifyDate($date)
{
//Given m/d/Y and returns date if valid, else NULL.
$d=explode('/',$date);
return ((isset($d[0])&&isset($d[1])&&isset($d[2]))?(checkdate($d[0],$d[1],$d[2])?$date:NULL):NULL);
}
You can try this one:
static public function verifyDate($date)
{
return (DateTime::createFromFormat('m/d/Y', $date) !== false);
}
This outputs true/false. You could return DateTime object directly:
static public function verifyDate($date)
{
return DateTime::createFromFormat('m/d/Y', $date);
}
Then you get back a DateTime object or false on failure.
UPDATE:
Thanks to Elvis Ciotti who showed that createFromFormat accepts invalid dates like 45/45/2014.
More information on that: https://stackoverflow.com/a/10120725/1948627
I've extended the method with a strict check option:
static public function verifyDate($date, $strict = true)
{
$dateTime = DateTime::createFromFormat('m/d/Y', $date);
if ($strict) {
$errors = DateTime::getLastErrors();
if (!empty($errors['warning_count'])) {
return false;
}
}
return $dateTime !== false;
}
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
function was copied from this answer or php.net
You could check this resource: http://php.net/manual/en/datetime.getlasterrors.php
The PHP codes states:
try {
$date = new DateTime('asdfasdf');
} catch (Exception $e) {
print_r(DateTime::getLastErrors());
// or
echo $e->getMessage();
}
Try this:
function is_valid_date($date,$format='dmY')
{
$f = DateTime::createFromFormat($format, $date);
$valid = DateTime::getLastErrors();
return ($valid['warning_count']==0 and $valid['error_count']==0);
}
$date[] = '20/11/2569';
$date[] = 'lksdjflskdj';
$date[] = '11/21/1973 10:20:30';
$date[] = '21/11/1973 10:20:30';
$date[] = " ' or uid like '%admin%";
foreach($date as $dt)echo date('Y-m-d H:i:s', strtotime($dt))."\n";
Output
1970-01-01 05:30:00
1970-01-01 05:30:00
1970-01-01 05:30:00
1973-11-21 10:20:30
1970-01-01 05:30:00
1970-01-01 05:30:00
I needed to allow user input in (n) different, known, formats...including microtime. Here is an example with 3.
function validateDate($date)
{
$formats = ['Y-m-d','Y-m-d H:i:s','Y-m-d H:i:s.u'];
foreach($formats as $format) {
$d = DateTime::createFromFormat($format, $date);
if ($d && $d->format($format) == $date) return true;
}
return false;
}
With the following an empty string like '' or 0 or '0000-00-00 00:00:00' is false
$valid = strtotime($date) > 0;
For me, the combination of date_parse and checkdate works best and it is almost one-liner:
$date="2024-02-29";
$dp=date_parse("$date");
if (sprintf("%04d-%02d-%02d",$dp['year'], $dp['month'], $dp['day'])===$date && checkdate($dp['month'], $dp['day'], $dp['year'])) {
// format is OK and date is valid
}

Categories