Viewed   70 times

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

 Answers

3

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://.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;
}
Monday, September 5, 2022
3

DateInterval is buggy on windows platform. See bug #51183. The official answer seems to be "use VC9 builds instead for now".

Monday, August 15, 2022
 
3

I use following wrapper class in my php5.2 apps: http://pastebin.ca/2051944. Untill php5.3 was released - it saves much my time

Thursday, November 3, 2022
 
3

If you choose a server mode for the MySQL server that doesn't allow invalid date values a query containing such a malformed date representation will cause an error instead of (silently) assuming 0000-00-00
see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html

e.g.

$pdo = new PDO('mysql:host=localhost;dbname=test', 'localonly', 'localonly'); 
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$pdo->exec('CREATE TEMPORARY TABLE foo (id int auto_increment, d datetime, primary key(id))');

$query = "INSERT INTO foo (d) VALUES ('2010-02-31 12:15:18')";
foreach( array('ALLOW_INVALID_DATES', 'STRICT_ALL_TABLES') as $mode ) {
  echo $mode, ": "; flush();
  $pdo->exec("SET SESSION sql_mode='$mode'");
  $pdo->exec($query);
  echo "Ok.n";
}

prints

ALLOW_INVALID_DATES: Ok.
STRICT_ALL_TABLES: 
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2010-02-31 12:15:18' for column 'd' at row 1' in [...]
Wednesday, August 17, 2022
1

You could use the TryParseExact method which allows you to pass a collection of possible formats that you want to support. The TryParse method is culture dependent so be very careful if you decide to use it.

So for example:

DateTime fromDateValue;
string s = "15/07/2012";
var formats = new[] { "dd/MM/yyyy", "yyyy-MM-dd" };
if (DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
{
    // do for valid date
}
else
{
    // do for invalid date
}
Saturday, October 1, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :