I'm trying to construct a DateTime object with multiple accepted formats.
According to the DateTime::createFromFormat
docs, the first parameter (format) must be a string. I was wondering if there was a way to createFromFormats.
In my case, I want the year for my format to be optional:
DateTime::createFromFormat('Y-m-d', $date);
DateTime::createFromFormat('m-d', $date);
so that a user can input just 'm-d'
and the year would be assumed 2013. If I wanted multiple accepted formats, would I have to call createFromFormat each time?
Shortest thing for my scenario is:
DateTime::createFromFormat('m-d', $date) ?: DateTime::createFromFormat('Y-m-d', $date);
You could create your own class that extends DateTime and add your own method:
class EasyDateTime extends DateTime {
public static function createFromFormat($string){
if (count(explode("-", $string)) === 2) {
$string = date('Y')."-".$string;
}
return parent::createFromFormat('Y-m-d',$string);
}
}
var_dump( EasyDateTime::createFromFormat('01-01') );
// object(DateTime)#1 (3) { ["date"]=> string(19) "2013-01-01 05:11:03" ["timezone_type"]=> int(3) ["timezone"]=> string(11) "Europe/Oslo" }