I am converting an ASP application to PHP and am having difficulty transcribing date validation functionality.
In ASP, I have the function isDate(), which allows me to validate a date regardless of its format. So if someone enters any of the following, isDate() returns true:
1/1/2012
January 1, 2012
Jan 12, 2010 1:00 pm
1/1/2012 1:32 pm
The benefit is that I can let the user enter the data and time in whatever format they choose. After that, with minimal effort, I can update a database without doing any post processing (assuming true is returned). E.g.:
UPDATE my_table SET date_field = @date_var WHERE my_id = @id_var
[note: SQL Server 2008]
With PHP, I’m finding that validating a date/time is more complex. I’ve reviewed the assorted questions posted here as well as the documentation and there doesn’t seem to be a straightforward way to validate a date or time or date/time combination easily.
I’m wondering if there are classes available to do the grunt work. Something that will work like isDate() and send me back a true/false based on a user entered date/time/date & time.
Thanks.
You can check the return value of strtotime()
to see if a date can be parsed:
if(strtotime($date) !== false) {
// valid date/time
}
This is also how to normalize all the dates, by storing them as the return value of strtotime()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With