Welcome to WebmasterWorld Guest from 54.162.227.136

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Converting String to DATETIME

     
7:29 am on Mar 16, 2005 (gmt 0)

10+ Year Member



What is the best way to go about inserting a DATETIME into my MySQL database via PHP? The scenario is that I have a form where the user will enter a date and time and submit. I want this form to insert a valid DATETIME value into my database. I know how to convert my DATETIME values into Unix timestamps for use in my PHP code, but I'm not understanding how to best handle it the other direction.

Given that the user would be inputting field values as follows:
$month
$day
$year
$hour(24)
$minutes

how do I best construct that into a valid DATETIME value that will go into my INSERT statement?

8:11 am on Mar 16, 2005 (gmt 0)

10+ Year Member



Something like this:

$datetime = date("r", strtotime("$year-$month-$day $hour:$minutes:00"));

;)

5:47 am on Mar 17, 2005 (gmt 0)

10+ Year Member



That didn't work for me, but after some more thought i realized the answer was much more simple:

$time = $year . "-" . $month . "-" . $day . " " . $hour . ":" . $minutes . ":00";

Works like a charm, I don't even have to have the leading zeros. I also added a radio button to my form so the user can select AM or PM. I then added this line before the above:

if ($ampm == "pm") { $hour = $hour + 12; }

6:03 am on Mar 17, 2005 (gmt 0)

10+ Year Member



Actually, that would cause problems in the cases of 12 am and 12 pm. This will convert it to a proper 24 hour format:

if ($ampm == "pm") { if ($hour!= "12") { $hour = $hour + 12; }}
if ($ampm == "am") { if ($hour == "12") { $hour = 0; }}

 

Featured Threads

Hot Threads This Week

Hot Threads This Month