4

How do you do the following in PHP?

Check to see a time passed into a function is a valid date or a timestamp (valid meaning after 1970 time)?

If neither, throw an error.

I was thinking

if(ctype_digit($time)) {
     if($time > time_in_1970) {
         // good
     } else {
         // bad
     }
} else {
   $date_from_time = strtotime($time);

   if($date_from_time === false) {
     // error

2 Answers2

2

You can do like below:

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

function was copied from this answer or php.net

Or you can use checkdate() function of php like below:

function IsDate( $Str )
{
  $Stamp = strtotime( $Str );
  $Month = date( 'm', $Stamp );
  $Day   = date( 'd', $Stamp );
  $Year  = date( 'Y', $Stamp );

  return checkdate( $Month, $Day, $Year );
}
Community
  • 1
  • 1
Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
  • That's good code to generally validate a date, but why use it? It's a timestamp. If it's a number, it can by definition never have an invalid value. – Pekka Dec 03 '13 at 02:20
  • 1
    The first code block copied from http://php.net/manual/en/function.checkdate.php without attribution. Please don't do that, it's plagiarism and not allowed. Always provide a link to the original source. Thanks! – Pekka Dec 03 '13 at 02:22
  • 1
    Not for the first code block. [PHP preg_match with working regex](http://stackoverflow.com/q/12322824) – Pekka Dec 03 '13 at 02:25
2

As long as the timestamp is greater than 0, it is a valid timestamp.

A timestamp of 0 = Dec 31, 1969

echo date("Y-m-d", 0);

This is because a UNIX timestamp is the measurement of seconds since the Epoch, AKA Dec 31, 1969

dockeryZ
  • 3,981
  • 1
  • 20
  • 28