homepage Welcome to WebmasterWorld Guest from 54.211.235.255
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Converting String to DATETIME
TheRealTerry




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

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?

 

dcrombie




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

Something like this:

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

;)

TheRealTerry




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

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; }

TheRealTerry




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

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; }}

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved