PHP DateTime accept multiple formats?

Posted by John Smith on Stack Overflow See other posts from Stack Overflow or by John Smith
Published on 2013-10-31T03:30:50Z Indexed on 2013/10/31 3:53 UTC
Read the original article Hit count: 92

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about php

Related posts about datetime