kaspernov
kaspernov

Reputation: 141

How to check string's date format in PHP?

I would like to check if the string has this time format:

Y-m-d H:i:s

and if not than do some code e.g.

if here will be condition do { this }
else do { this }

How to do this condition in PHP?

Upvotes: 11

Views: 34193

Answers (7)

Surendra Kumar Ahir
Surendra Kumar Ahir

Reputation: 1687

How to check string's date format in PHP?

 if (DateTime::createFromFormat('Y-m-d G:i:s', $myString) !== FALSE) {
 echo 'true';
}                                                               

Upvotes: 20

cwallenpoole
cwallenpoole

Reputation: 82018

You don't. It is impossible to tell if it is Y-m-d or Y-d-m, or even Y-d-d vs Y-m-m. What is 2012-05-12? May 12th or Dec. 5?

But, if you are content with that, you can always do:

// convert it through strtotime to get the date and back.
if( $dt == date('Y-m-d H:i:s',strtotime($dt)) )
{
    // date is in fact in one of the above formats
}
else
{
    // date is something else.
}

Though you might want to see if preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/',$date) isn't faster on this. Haven't tested it.

Upvotes: 18

Marc B
Marc B

Reputation: 360642

if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $yourdate)) {
   // it's in the right format ...
} else {
  // not the right format ...
}

Note that this only checks that the date string looks like a bunch of digits separated by colons and dashes. It does NOT check for oddities like '2011-02-31' (Feb 31st) or '99:99:99' for a time (99 o'clock?).

Upvotes: 3

Pedro Lobito
Pedro Lobito

Reputation: 98901

From php.net

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

Upvotes: 1

Shad
Shad

Reputation: 15451

preg_match is what you are looking for, specifically:

if(preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/',$date)){
   //dothis
}else{
   //dothat
}

if you REALLY ONLY want properly formatted date, then

/\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d:[0-5]\d/

Upvotes: 21

SeanCannon
SeanCannon

Reputation: 77966

You could always just force it:

date('Y-m-d H:i:s',strtotime($str));

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

The answer probably involves regular expressions. I suggest reading this documentation, and then coming back here if you're still having trouble.

Upvotes: -2

Related Questions