views:

520

answers:

1

This is a double question in terms of front end usability and PHP DATE_TIME validation.

I am working on a site for a client who would like to add the date he finished a project (so the projects can be listed in that order). He will be the only one using the admin interface, so I would like it to be as simple as possible.

I am storing the dates as DATE_TIME in a SQLite db.

I would like to require the client enter at least the year and month, with the option to add day, hour, minute, second to the DATE_TIME. If these are not set they will default to the smallest number.

I thought the best way and easiest to do this was making a single input form taking the input(left) and making the result(right). Making him use xxxx/xx/xx/xx/xx/xx as the format.

2009/08       = 2009-08-01 00:00:01
2009/08/01    = 2009-08-01 00:00:01
2009/08/01/05 = 2009-08-01 05:00:01

(adding one second as default otherwise it will be the day before)

I tried first by exploding the input into an array and validating each date section with regex. it got messy real fast and I can't figure out how to validate the proper ranges, say, /[1980-2009]/ or /[01-12]/ (that doesn't work like I expected). Also /[(0-9){2}]/ isn't going to work for the month obviously.

Another option is making each date section a separate select field. Making each field after month optional. But that gets messy in the html output, also given that each month doesn't have 31 days, I would need some javascript to change the day field depending on what month is selected. That's too much. It also seems a lot easier and faster to use a single field.

What do you guys suggest is the best way to input and validate custom datetimes?

+5  A: 

I would reccomend calling strtotime() on the date, that way he can enter a variety of date formats, including month/year, day/month/year, day/month/year hours:minutes, and year-month-day hours:minutes

If strtotime can't determine what the date is, it returns false (or -1 in older versions of PHP, check your manual). SO your general code would be:

  1. Run input through stripslashes (if needed) and strtotime
  2. Check if value is === false. If so, display error
  3. Otherwise, format the time as yor database expects is using date()
Josh
That's it! Thanks. Boy that's a lot easier.
It doesn't seem to just take just the year/month... meh, I will make him enter a day too. Great flexibility in that function! Thanks again for pointing it out!
You're right -- I was incorrect. With only one slash, i.e. 8/1, the function assumes that's month/day(/current year)
Josh
If you wanted to support just month/year or month-year, or something else that strtotime isn't accepting, you could search for that pattern *before* calling strtotime. Let me know if you need help with that.
Josh
I can handle that, but this solution is just fine. I have to say again I am so pleased to take this from 110 lines to 5.
Glad I could help. strtotime() is a great function!
Josh