Search code examples
phpjavascriptdatejs

PHP strtotime() vs. date.js parse()


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


Solution

  • 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:

    Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

    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 and 5-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.

    echo date("Y-M-n", strtotime("5/1/12"));
    // 2012-May-5
    echo date("Y-M-n", strtotime("5-1-12"));
    // 2005-Jan-1 (whoops!)
    

    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.