简体   繁体   English

在数据库中转换/保存用户提交的“时间”

[英]Convert/Save User Submitted “Time” in database

I have a form where users select a time from a form我有一个表格,其中用户 select 一次来自表格

    <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.我将此信息发布到一个处理页面,我需要在其中以 DateTime 格式保存用户在数据库中提交的时间。 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.数据需要以日期时间格式(2011-06-11 23:11:07)存储在数据库中,日期为今天的日期。

I'm thinking that the data function will some how be able to convert it, but I can't seem to figure it out.我在想数据 function 将如何转换它,但我似乎无法弄清楚。

Easy enough.很容易。 Assuming the user enters 1:09pm, then:假设用户在下午 1:09 输入,则:

$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.还有其他方法可以解决这个问题,但这可能更容易理解。

strtotime() will convert a string input into a timestamp. strtotime()将字符串输入转换为时间戳。 Then you can use this timestamp and the date() function to format the date in any way you like.然后您可以使用此时间戳和date() function 以您喜欢的任何方式格式化日期。

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.您应该向它传递一个格式类似于“YYYY-MM-DD HH:MM:SS”的字符串,它应该可以毫无问题地为您解析它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM