I'm receiving a date string from an API, and it is formatted as yyyy-mm-dd
.
I am currently using a regex to validate the string format, which works ok, but I can see some cases where it could be a correct format according to the string but actually an invalid date. i.e. 2013-13-01
, for example.
Is there a better way in PHP to take a string such as 2013-13-01
and tell if it is a valid date or not for the format yyyy-mm-dd
?
Determine if string is a date, even if string is a non-standard format
(strtotime doesn't accept any custom format)
This option is not only simple but also accepts almost any format, although with non-standard formats it can be buggy.
Tested Regex solution:
This will return null if the date is invalid or is not yyyy-mm-dd format, otherwise it will return the date.
I have this thing that, even with PHP, I like to find functional solutions. So, for example, the answer given by @migli is really a good one, highly flexible and elegant.
But it has a problem: what if you need to validate a lot of DateTime strings with the same format? You would have to repeat the format all over the place, what goes against the DRY principle. We could put the format in a constant, but still, we would have to pass the constant as an argument to every function call.
But fear no more! We can use currying to our rescue! PHP doesn't make this task pleasant, but it's still possible to implement currying with PHP:
So, what we just did? Basically we wrapped the function body in an anonymous and returned such function instead. We can call the validation function like this:
Yeah, not a big difference... but the real power comes from the partially applied function, made possible by currying:
Functional programming FTW!
You can use
DateTime
class for this purpose:[Function taken from this answer. Also on php.net. Originally written by Glavić.]
Test cases:
Demo!
Use in simple way with php prebuilt function:
Test