Rich Darvins
Rich Darvins

Reputation: 371

How to ensure a valid date in PHP?

I have been using the date_parse method for input validation, which seems to be just fine... except it's not actually validating the date for correctness.

For example:

date_parse("2010/9/31/"); // returns FALSE 
date_parse("2010-9-31"); // should return FALSE!

How can I get it to validate that 2010-9-31 is, in fact, an invalid date?

Upvotes: 2

Views: 378

Answers (4)

manutter
manutter

Reputation: 133

$d = date_parse("2010-9-31");
if(count($d["warnings"]) > 0) { 
  echo array_shift($d["warnings"]) . "\n"; 
}

// --> "The parsed date was invalid"

Upvotes: 0

cwallenpoole
cwallenpoole

Reputation: 82078

To be clear, 2010-9-31 is a valid date, so the return you're getting is correct behavior.

If you're trying to force a specific format, you may want to use date_parse_from_format

print_r(date_parse_from_format("Y.n.j", $date));

Or, if that isn't sufficient, use preg_match on $date before parsing it. If you do decide to use preg_match, you may want to ask a second question.

Upvotes: 1

Adam Kiss
Adam Kiss

Reputation: 11859

<?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; 
} 
?>

source: http://php.net/manual/en/function.checkdate.php

Upvotes: 3

karim79
karim79

Reputation: 342765

If you mean what I think you mean, then you should take a look at checkdate.

var_dump(checkdate(12, 31, 2000)); // true
var_dump(checkdate(2, 29, 2001)); // false, because was not a leap year

Upvotes: 0

Related Questions