Jason Small
Jason Small

Reputation: 1054

Convert/Save User Submitted "Time" in database

I have a form where users select a time from a form

    <select name='hour'>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='3'>3</option>
    <option value='4'>4</option>
    <option value='5'>5</option>
    <option value='6'>6</option>
    <option value='7'>7</option>
    <option value='8'>8</option>
    <option value='9'>9</option>
    <option value='10'>10</option>
    <option value='11'>11</option>
    <option value='12'>12</option>
</select>
:
<select name='min'>
    <option value='00'>00</option>
    <option value='15'>15</option>
    <option value='30'>30</option>
    <option value='45'>45</option>

</select>
<select name='ampm'>
    <option value='AM'>AM</option>
    <option value='PM'>PM</option>
</select>

I'm posting this information to a processing page where I need to save the time that the user submitted in the database in DateTime format. The data will need to be stored in the database in the datetime format (2011-06-11 23:11:07) with the date being today's date.

I'm thinking that the data function will some how be able to convert it, but I can't seem to figure it out.

Upvotes: 0

Views: 294

Answers (2)

Marc B
Marc B

Reputation: 360682

Easy enough. Assuming the user enters 1:09pm, then:

$hour = intval($_REQUEST['hour']); // 1
$min = intval($_REQUEST['minute']); // 9
if (($_REQUEST['ampm'] == 'PM') && ($hour <> 12)) { 
   $hour += 12; // adjust for 24 clock, so $hour becomes 13
}

$timestring = sprintf('%02d:%02d:00', $hour, $min); // 13:09:00
$datestring = date('Y-m-d'); // 2011-06-12

$timestamp = $datestring . ' ' . $timestring; // 2011-06-12 13:09:00

There's other ways of going about this, but this is probably a bit easier to understand.

Upvotes: 2

Sam Becker
Sam Becker

Reputation: 19636

strtotime() will convert a string input into a timestamp. Then you can use this timestamp and the date() function to format the date in any way you like.

You should pass it a string with a format similar to "YYYY-MM-DD HH:MM:SS" and it should parse it for you with no problems.

Upvotes: 0

Related Questions