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?
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?
How to check string's date format in PHP?
if (DateTime::createFromFormat('Y-m-d G:i:s', $myString) !== FALSE) {
echo 'true';
}
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.
Y-m-m: 2012-05-12... May the Decemberth of 2012.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?).
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;
}
?>
The answer probably involves regular expressions. I suggest reading this documentation, and then coming back here if you're still having trouble.