tags:

views:

204

answers:

4

I have a couple textboxes that allows a person to enter a time and date. The time is entered with a textbox for hours, a textbox for minutes, a drop down for am/pm and some drop downs for months/hours/years

So, I'd like to combine all of these to create a timestamp out of it and save it to the database.

But i've confused myself in how to do all that to create a proper timestamp, especially with the AM/PM part.

+2  A: 

It sounds like you'd just use mktime(). Get the correct hour number by adding 12 for pm, then pass the arguments into the function.

if($is_pm) $hour += 12;
$time = mktime($hour, $minute, $second, $month, $day, $year);

If you're looking for a MySQL timestamp instead of a UNIX timestamp, you have two options:

  1. Build the timestamp in MySQL's format using date(): date('Y-m-d H:i:s', $time);
  2. Let MySQL do it for you: UPDATE table SET date = FROM_UNIXTIME($time) WHERE foo='bar'

Or you could just store the integer timestamp in the database as an integer.

Matchu
oh my that's ridiculously easy. How i didn't even consider that is pretty silly. Thank You!
scatteredbomb
A: 

strtotime will do this:

$timestamp = strtotime("$year-$month-$day $hours:$minutes $am_pm");

Just make sure to zero-pad $month, $day, $hours, and $minutes.

abeger
I'd expect mktime would have better performance than parsing a string, however.
Matchu
You're probably right, but I traded off a slight performance hit for simpler handling of AM/PM.
abeger
A: 

You can use the following to convert it to a unix timestamp:

strtotime("2009/01/02 12:13:14 PM");
strtotime("2009/01/02 12:13:14 AM");

PHP Manual reference: http://php.net/manual/en/function.strtotime.php

ar
Not what the question asked.
Matchu
+1  A: 

Assuming that you've already checked for valid input, you can use the mktime() function. If PM is selected, just add 12 to the hours. That will give you back a Unix Timestamp. You can pass that result to date() to format the date however you would like.

smack0007