Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best method to input and validate custom datetime in PHP form

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?

like image 894
user73119 Avatar asked Mar 01 '23 11:03

user73119


1 Answers

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()
like image 94
Josh Avatar answered Apr 28 '23 00:04

Josh