Here is another crooked way to check if given data is valid DATETIME or not.
function checkDateTime($data) {
if (date('Y-m-d H:i:s', strtotime($data)) == $data) {
return true;
} else {
return false;
}
}
checkdate
(PHP 4, PHP 5)
checkdate — Validate a Gregorian date
Description
bool checkdate
( int
$month
, int $day
, int $year
)Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.
Parameters
-
month -
The month is between 1 and 12 inclusive.
-
day -
The day is within the allowed number of days for the given
month. Leapyears are taken into consideration. -
year -
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
<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>
The above example will output:
bool(true) bool(false)
See Also
- mktime() - Get Unix timestamp for a date
- strtotime() - Parse about any English textual datetime description into a Unix timestamp
bharath.kishore.a AT gmail. DOT com
07-Mar-2012 04:00
pmmmm
18-Feb-2012 01:56
Here's a function that further builds on top of what was posted earlier (bmauser and ystein M). It takes date and format (D, DD, M, MM, YY, YYYY) and any seperator. Format example: YYYY-MM-DD. The previous functions didn't take dashes and required specific order.
<?php
function valid_date($date, $format = 'YYYY-MM-DD'){
if(strlen($date) >= 8 && strlen($date) <= 10){
$separator_only = str_replace(array('M','D','Y'),'', $format);
$separator = $separator_only[0];
if($separator){
$regexp = str_replace($separator, "\\" . $separator, $format);
$regexp = str_replace('MM', '(0[1-9]|1[0-2])', $regexp);
$regexp = str_replace('M', '(0?[1-9]|1[0-2])', $regexp);
$regexp = str_replace('DD', '(0[1-9]|[1-2][0-9]|3[0-1])', $regexp);
$regexp = str_replace('D', '(0?[1-9]|[1-2][0-9]|3[0-1])', $regexp);
$regexp = str_replace('YYYY', '\d{4}', $regexp);
$regexp = str_replace('YY', '\d{2}', $regexp);
if($regexp != $date && preg_match('/'.$regexp.'$/', $date)){
foreach (array_combine(explode($separator,$format), explode($separator,$date)) as $key=>$value) {
if ($key == 'YY') $year = '20'.$value;
if ($key == 'YYYY') $year = $value;
if ($key[0] == 'M') $month = $value;
if ($key[0] == 'D') $day = $value;
}
if (checkdate($month,$day,$year)) return true;
}
}
}
return false;
}
?>
Anonymous
14-Feb-2012 01:10
This is a very good function to check if a date format is valid (with regex).
For example:
2012-2-28 = Valid
2012-2-29 = Valid (leap year)
2012-2-30 = Invalid
2012-1-30 = Valid
2012-1-31 = Valid
2012-2-32 = Invalid
Ensure there are no spaces in the preg_match function:
<?php
function Valid_Date_Format($date)
{
$converted=str_replace('/','-',$date);
if(preg_match("/^((((19|20)(([02468][048])|([13579][26]))-02-29))|((20[0-9][0-9])|(19[0-9][0-9]))-((((0[1-9])|
(1[0-2]))-((0[1-9])|(1\d)|(2[0-8])))|((((0[13578])|(1[02]))-31)|(((0[1,3-9])|
(1[0-2]))-(29|30)))))$/",$converted)===1)
{
return TRUE;
}
return FALSE;
}
?>
I don't know where I got the original code from but I've not found anything better.
pradeepkumarprajapati3 at yahoo dot co dot in
19-Dec-2011 01:23
don't use strtotime() to format inputs to checkdate(). It would give false results.
Eg,
Below function would return true though it should have been false
<?php
$str = '2011-11-31'; //invalid date, november has 30 days only
function isDateValid($str)
{
$stamp = strtotime($str);
if (!is_numeric($stamp))
return FALSE;
//checkdate(month, day, year)
if ( checkdate(date('m', $stamp), date('d', $stamp), date('Y', $stamp)) )
{
return TRUE;
}
return FALSE;
}
?>
The reason is that strtotime() coverts 2011-11-31 to 2011-12-01.
check with date('Y-m-d', strtotime('2011-11-31'))
Anonymous
13-Jul-2009 03:06
Beware that checkdate can not be used as validation to check if a date is correct.
The example below will return bool(true) which can result that the <script> part is inserted into the database.
<?php
$date = "01-01-1980 <script>alert('test');</script>";
$aDate_parts = preg_split("/[\s-]+/", $date);
var_dump(
checkdate(
$aDate_parts[1], // Month
$aDate_parts[0], // Day
$aDate_parts[2] // Year
)
);
?>
iamcanadian1973 at gmail dot com
17-Apr-2009 12:37
[NOTE BY danbrown AT php DOT net: The author's purpose for this function is to determine whether or not a given string $str is a date using a static algorithm.]
<?php
function is_date( $str )
{
$stamp = strtotime( $str );
if (!is_numeric($stamp))
{
return FALSE;
}
$month = date( 'm', $stamp );
$day = date( 'd', $stamp );
$year = date( 'Y', $stamp );
if (checkdate($month, $day, $year))
{
return TRUE;
}
return FALSE;
}
?>
rfeugenio at gmail dot com
27-Mar-2009 12:21
<?php
// This is a simple function that will get the last day of the month.
function GetLastDayofMonth($year, $month) {
for ($day=31; $day>=28; $day--) {
if (checkdate($month, $day, $year)) {
return $day;
}
}
}
?>
James Luckhurst
22-Mar-2009 06:26
<?php
/*
## converts a given date format to another date format returns date if the checked date given is valid; otherwise returns NULL
## $s_date the date in e.g. dd/mm/yyyy
## $s_from, $s_to date formats from to i.e. convertdate('13/04/2009','eng','iso','-'); output: 2009-04-13
## date formats available
## 'eng' = dd/mm/yyyy
## 'usa' = mm/dd/yyyy
## 'iso' = yyyy/mm/dd
## $s_return_delimiter returned delimiter e.g. '-' would return dd-mm-yyyy
*/
function convertdate($s_date,$s_from,$s_to,$s_return_delimiter) {
$s_return_date = '';
$s_from = strtolower($s_from);
$s_to = strtolower($s_to);
$s_date = str_replace(array('\'', '-', '.', ',', ' '), '/', $s_date);
$a_date = explode('/', $s_date);
switch($s_from) {
case 'eng': # dd/mm/yyyy
$day = $a_date[0];
$month = $a_date[1];
$year = $a_date[2];
break;
case 'usa': # mm/dd/yyyy
$month = $a_date[0];
$day = $a_date[1];
$year = $a_date[2];
break;
case 'iso': # yyyy/mm/dd
$year = $a_date[0];
$month = $a_date[1];
$day = $a_date[2];
break;
default: # error message
user_error('function convertdate(string $s_date, string $s_from, string $s_to, string $s_return_delimiter) $s_from not a valid type of \'eng\', \'usa\' or \'iso\'');
return NULL;
}
# substitution fixes of valid alternative human input e.g. 1/12/08
if (strlen($day)==1) { $day='0'.$day; } # day -trailing zero missing
if (strlen($month)==1) { $month='0'.$month; } # month -trailing zero missing
if (strlen($year)==3) { $year=substr(date('Y'),0,strlen(date('Y'))-3).$year; } # year -millennium missing
if (strlen($year)==2) { $year=substr(date('Y'),0,strlen(date('Y'))-2).$year; } # year -century missing
if (strlen($year)==1) { $year=substr(date('Y'),0,strlen(date('Y'))-1).$year; } # year -decade missing
switch($s_to) {
case 'eng': # dd/mm/yyyy
$s_return_date = $day.$s_return_delimiter.$month.$s_return_delimiter.$year;
break;
case 'usa': # mm/dd/yyyy
$s_return_date = $month.$s_return_delimiter.$day.$s_return_delimiter.$year;
break;
case "iso": # yyyy/mm/dd
$s_return_date = $year.$s_return_delimiter.$month.$s_return_delimiter.$day;
break;
default: # error message
user_error('function convertdate(string $s_date, string $s_from, string $s_to, string $s_return_delimiter) $s_to not a valid type of \'eng\', \'usa\' or \'iso\'');
return NULL;
}
# if it's an invalid calendar date e.g. 40/02/2009 or rt/we/garbage
if (!is_numeric($month) || !is_numeric($day) || !is_numeric($year)) {
return NULL;
} elseif (!checkdate($month, $day, $year)) {
return NULL;
}
return $s_return_date;
}
echo convertdate('13/04/2009','eng','iso','-');
?>
ystein M
18-Mar-2009 07:51
I think there is an error in the function from bmauser below. $regexp is overwritten. Here's another version which also accepts missing zeros and two digits year notation.
This function checks date if matches given format and validity of the date.
<?php
/**
* Checks date if matches given format and validity of the date.
* Examples:
* <code>
* is_date('22.22.2222', 'mm.dd.yyyy'); // returns false
* is_date('11/30/2008', 'mm/dd/yyyy'); // returns true
* is_date('30-01-2008', 'dd-mm-yyyy'); // returns true
* is_date('2008 01 30', 'yyyy mm dd'); // returns true
* </code>
* @param string $value the variable being evaluated.
* @param string $format Format of the date. Any combination of <i>mm<i>, <i>dd<i>, <i>yyyy<i>
* with single character separator between.
*/
function is_valid_date($value, $format = 'dd.mm.yyyy'){
if(strlen($value) >= 6 && strlen($format) == 10){
// find separator. Remove all other characters from $format
$separator_only = str_replace(array('m','d','y'),'', $format);
$separator = $separator_only[0]; // separator is first character
if($separator && strlen($separator_only) == 2){
// make regex
$regexp = str_replace('mm', '(0?[1-9]|1[0-2])', $format);
$regexp = str_replace('dd', '(0?[1-9]|[1-2][0-9]|3[0-1])', $regexp);
$regexp = str_replace('yyyy', '(19|20)?[0-9][0-9]', $regexp);
$regexp = str_replace($separator, "\\" . $separator, $regexp);
if($regexp != $value && preg_match('/'.$regexp.'\z/', $value)){
// check date
$arr=explode($separator,$value);
$day=$arr[0];
$month=$arr[1];
$year=$arr[2];
if(@checkdate($month, $day, $year))
return true;
}
}
}
return false;
}
?>
[NOTE BY danbrown AT php DOT net: Original function was written by (bmauser AT gmail) on 16-DEC-2008.]
sebagr@gmail
04-Mar-2009 11:20
Here's a nice snippet to check if user input is valid:
<?php
$date_format = 'Y-m-d';
$input = '2009-03-03';
$input = trim($input);
$time = strtotime($input);
$is_valid = date($date_format, $time) == $input;
print "Valid? ".($is_valid ? 'yes' : 'no');
?>
venadder at yahoo dot ca
22-Jan-2009 12:49
Here is a simple IsDate function, using purely PHP functions( A Check for $Stamp can be added to see if it's a legal Unix timestamp ):
<?php
function IsDate( $Str )
{
$Stamp = strtotime( $Str );
$Month = date( 'm', $Stamp );
$Day = date( 'd', $Stamp );
$Year = date( 'Y', $Stamp );
return checkdate( $Month, $Day, $Year );
}
?>
parris dot varney at gmail dot com
10-Dec-2008 09:24
I put together an is_date function using checkdate. Works the same as is_numeric.
<?php
public static function is_date($date)
{
$date = str_replace(array('\'', '-', '.', ','), '/', $date);
$date = explode('/', $date);
if( count($date) == 1 // No tokens
and is_numeric($date[0])
and $date[0] < 20991231 and
( checkdate(substr($date[0], 4, 2)
, substr($date[0], 6, 2)
, substr($date[0], 0, 4)))
)
{
return true;
}
if( count($date) == 3
and is_numeric($date[0])
and is_numeric($date[1])
and is_numeric($date[2]) and
( checkdate($date[0], $date[1], $date[2]) //mmddyyyy
or checkdate($date[1], $date[0], $date[2]) //ddmmyyyy
or checkdate($date[1], $date[2], $date[0])) //yyyymmdd
)
{
return true;
}
return false;
}
?>
doob_ at gmx dot de
26-Nov-2008 10:47
<?php
/*
** check a date
** dd.mm.yyyy || mm/dd/yyyy || dd-mm-yyyy || yyyy-mm-dd
*/
function check_date($date) {
if(strlen($date) == 10) {
$pattern = '/\.|\/|-/i'; // . or / or -
preg_match($pattern, $date, $char);
$array = preg_split($pattern, $date, -1, PREG_SPLIT_NO_EMPTY);
if(strlen($array[2]) == 4) {
// dd.mm.yyyy || dd-mm-yyyy
if($char[0] == "."|| $char[0] == "-") {
$month = $array[1];
$day = $array[0];
$year = $array[2];
}
// mm/dd/yyyy # Common U.S. writing
if($char[0] == "/") {
$month = $array[0];
$day = $array[1];
$year = $array[2];
}
}
// yyyy-mm-dd # iso 8601
if(strlen($array[0]) == 4 && $char[0] == "-") {
$month = $array[1];
$day = $array[2];
$year = $array[0];
}
if(checkdate($month, $day, $year)) { //Validate Gregorian date
return TRUE;
} else {
return FALSE;
}
}else {
return FALSE; // more or less 10 chars
}
}
check_date('21.02.1983');
check_date('21-02-1983');
check_date('02/21/1983'); // Common U.S. writing
check_date('1983-02-21'); // iso 8601
?>
saturn at ax dot com dot tw
26-Aug-2008 02:06
I wrote a simple function to converter datetime to UNIX timestamp. If the input time with error format, the function will return current timestamp.
<?php
function datetime2timestamp($datetime)
{
$datetime = str_replace('-', ' ', $datetime);
$datetime = str_replace('/', ' ', $datetime);
$datetime = str_replace(':', ' ', $datetime);
$array = explode(' ', $datetime);
$year = $array[0];
$month = $array[1];
$day = $array[2];
$array[3] ? $hour = $array[3] : $hour = '00';
$array[4] ? $minute = $array[4] : $minute = '00';
$array[5] ? $second = $array[5] : $second = '00';
if (preg_match("/^(\d{4}) (\d{2}) (\d{2}) ([01][0-9]|2[0-3]) ([0-5][0-9]) ([0-5][0-9])$/", "$year $month $day $hour $minute $second", $matches)) {
if (checkdate($matches[2], $matches[3], $matches[1])) {
return mktime(intval($hour), intval($minute), intval($second), intval($month), intval($day), intval($year));
} else {
return time();
}
} else {
return time();
}
}
?>
el dot vartauy__ at t__gmail dot com
29-Feb-2008 12:18
for funny leap year detection:
<?php
function is_leap($year=NULL) {
return checkdate(2, 29, ($year==NULL)? date('Y'):$year); // true if is a leap year
}
?>
wasile_ro[at]yahoo[dot]com
08-Oct-2007 10:30
here's a cool function to validate a mysql datetime:
<?php
function isValidDateTime($dateTime)
{
if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) {
if (checkdate($matches[2], $matches[3], $matches[1])) {
return true;
}
}
return false;
}
?>
jens wittmann
28-Aug-2007 11:29
for checking the rime use this:
<?php
function checktime($hour, $minute) {
if ($hour > -1 && $hour < 24 && $minute > -1 && $minute < 60) {
return true;
}
}
?>
brenig code
14-Aug-2007 02:21
<?php
/**
* check a date combo of the 2
*/
function checkData($date)
{
if (!isset($date) || $date=="")
{
return false;
}
list($dd,$mm,$yy)=explode("/",$date);
if ($dd!="" && $mm!="" && $yy!="")
{
if (is_numeric($yy) && is_numeric($mm) && is_numeric($dd))
{
return checkdate($mm,$dd,$yy);
}
}
return false;
}
?>
a34 at yahoo dot com
09-Jul-2007 08:21
checkData function posted below does not consider a date entered such as 03/27c/2000. The c will cause it to crash. Here is the fix.
<?php
function checkData($mydate) {
list($yy,$mm,$dd)=explode("-",$mydate);
if (is_numeric($yy) && is_numeric($mm) && is_numeric($dd))
{
return checkdate($mm,$dd,$yy);
}
return false;
}
?>
manuel84**at**mp4**dot**it
04-Dec-2006 09:49
If you have a date like this gg/mm/aaaa and you'd like to verify that it is in the Italian Format you can use a function like this.
For other date format you can take this code and simply modify the list and explode line
<?php
/**
* check a date in the Italian format
*/
function checkData($date)
{
if (!isset($date) || $date=="")
{
return false;
}
list($dd,$mm,$yy)=explode("/",$date);
if ($dd!="" && $mm!="" && $yy!="")
{
return checkdate($mm,$dd,$yy);
}
return false;
}
?>
