Search code examples
phpjavascriptdatetimedatepicker

How to make a nice "date picker" in PHP?


I'm doing some experimenting with MySQL and PHP, and I'm curious about creating a nice "date picker", e.g. picking the date 2010-11-11 (today's date).

I want to store valid DATETIME values in my MySQL database, and I want a PHP page to provide rolling lists for year, month and day (e.g. 2010-11-11) so as to avoid forcing the user to write in dates manually in a form and then do checking.

My question is, let's say the user picks the date 2010-11-31 (which doesn't exist); how can I create the simple rolling lists so as to adjust dynamically? That is, the user FIRST picks the year, then the month, and lastly the day (which is dynamically altered to accommodate the actual number of days in the given month). Hopefully leap years will also be taken care of. After picking them all and the user presses submit, the script will submit a correctly formatted DATETIME value to the database (e.g. YYYY-MM-DD, or YYYYMMDD).

As far as I have understood, the DATETIME type is strict as standard, meaning the server will keep track of invalid dates, which should be sufficiently easy to error-check. But I want to avoid this by doing what I described above.

Would you say my described 'solution' is easy to implement using only PHP (and MySQL)? Or would I need some other stuff (e.g. AJAX/JavaScript, JQuery etc.) to manage this? Any suggestions and pointers are very welcome, especially alternative approaches to the same problem that may be easier to implement. Thanks in advance!


Solution

  • There is a lot of JavaScript-based calendar widgets out there already. If you're not looking to do this for learning purposes, no reason to reinvent the wheel.

    Server-side validation is of course still mandatory, but those widgets will make it impossible for the user to select an invalid date under normal circumstances.

    E.g.