I've got a website where users can potentially type in their own dates before they're sent to the server. So I obviously need to parse what they give me and get it into a standard format before actually using it. So I used PHP's strtotime() function, which is pretty forgiving about what it will accept as input.
But I'm also using date.js on the site and its parse() function is pretty good, too. Should I use that on the user input before sending it to the server? Which one is better?
I'll keep strtotime() on the back end for safety, but if date.js is better I'll add that to the client.
(To clarify, I'm expecting mostly American date formats. But should that change, anything that eases that transition is preferred.)
As long as you feel
strtotime()
is meeting your needs, there isn't a great reason to change it on the client side. However,strtotime()
makes a couple of assumptions which you need to stay on top of:From the
strtotime()
documentation:If you are allowing your client to send the date in any format they choose, the above could be a source of confusion. I just tested the dates
5/1/12
and5-1-12
in date.js, and both were parsed as May 1st, 2012. PHP would interpret the two as May 1st 2012 and Jan 12th 2005(!!) respectively.However, pre-formatting the date has the obvious benefit of some insurance that the entered date is valid. Keeping
strtotime()
on the backend also ensures that you don't need a JavaScript-enabled client to send requests. Your PHP could still be called as a web service, etc, without the client needing to be a web browser.