Reputation: 1645
I need to check if a date have a format to save it or no, I use the function strptime() :
if (!strptime($contact[14], '%Y') && isset($contact[14]) && $contact[14] != ""){
$date_naissance = $contact[14];
dsm("BON FORMAT : ".$contact[14]);
} else {
$date_naissance = null;
dsm("MAUVAIS FORMAT : ".$contact[14]);
}
The problem is that the format seems not working, i need to validate all date with format year (like this : 2010, 2020, ..) but they are not validate, I don't understand why, in the php date documentation the Y is for a 4 digit year representation.
Anyone have an idea ?
Edit : with CreateFromFormat :
if(DateTime::createFromFormat('Y', $contact[22])){
dsm("Bon format : ".$contact[22]);
$date_derniere_inscription = strtotime($contact[22]);
} else {
$date_derniere_inscription = null;
}
But the date with only two digits and even the date with 0 value are validated too.
The 'Y' format seems doesn't work, with all the values (for example, 2012 but also 96 or 0) it create a date, with a 0 value it create '0000-07-11 10:38:45.000000' .. what is wrong with this format ?
Upvotes: 0
Views: 281
Reputation: 414
You can use a simple regular expression to do this.
/(\d{4})/
Sample code:
<?php
$pattern = "/(\d{4})/";
$year = "2015";
if(preg_match($pattern, $year)){
echo "Format correct!";
} else{
echo "Format incorrect!";
}
?>
For more information on regex, check the PHP Manual and the REGEX Builder & Tester
Upvotes: 0
Reputation: 4840
createFromFormat can help in this case. It will return false if given date string will not in given format.
$date = DateTime::createFromFormat('Y-m-d', '11-Jan-2018');
if ($date) {
echo 'In format';
} else {
echo 'Not in format';
}
For resetting all fields (Month, day, Minutes, seconds) except year, you can use:
$date = DateTime::createFromFormat('Y|', '2012');
And output will be: 2012-01-01 00:00:00.000000
. Can be converted to any format using format() function.
Upvotes: 2