简体   繁体   English

MYSQL格式化时间12小时

[英]Formatting Time 12 Hour Clock for MYSQL

How could a string be formatted depending an am/pm value so it could then be passed through strtotime and date? 如何根据am / pm值格式化字符串,然后将其传递给strtotime和date?

I have a form with two inputs and one select element. 我有一个带有两个输入和一个选择元素的表单。

  • Hour (input) <- (String) from 1 through 12 小时(输入)<-(字符串)从1到12
  • Minute (input) <- (String) from 0 through 59 分钟(输入)<-(字符串)从0到59
  • AM/PM (select) <- (String) am or pm AM / PM(选择)<-(字符串)am或pm

Need to insert to MySql type DATETIME which needs formatting to be current day + user selected time . 需要插入MySql类型的DATETIME,需要格式化为当前日期+用户选择的时间

Possible String: '2:34:pm' which for insert formatted to '2012-03-22 14:34:00' 可能的字符串:“ 2:34:pm”,用于插入的格式为“ 2012-03-22 14:34:00”

I read possible duplicate question, but I believe was difference scenario. 我读了可能重复的问题,但我相信是不同的情况。

Step 1 第1步
Generate UNIX timestamp (number of seconds since January 1, 1970). 生成UNIX时间戳(自1970年1月1日以来的秒数)。

$time = mktime($_POST["hour"], $_POST["minute"], 0);

$_POST["hour"] should be in 24-hour format. $_POST["hour"]应该为24小时格式。 You'll need to do basic input checking to ensure the values for $_POST["hour"] and $_POST["minute"] are valid. 您需要进行基本的输入检查,以确保$_POST["hour"]$_POST["minute"]的值有效。

To convert 12-hour to 24-hour time: 要将12小时制转换为24小时制:

if ($_POST["ampm"] == "pm")
    $_POST["hour"] = ($_POST["hour"] % 12) + 12;

Step 2 第2步
Store to MySQL. 存储到MySQL。

mysql_query("INSERT INTO table (date) VALUES (FROM_UNIXTIME($time))");

FROM_UNIXTIME(timestamp) will convert PHP's UNIX timestamp to a perfectly-formatted MYSQL date. FROM_UNIXTIME(timestamp)将PHP的UNIX时间戳转换为格式正确的MYSQL日期。

Presto! 普雷斯托!

Assuming your variables are named $hour , $minute , and $ampm : 假设您的变量名为$hour$minute$ampm

$datetime = date('Y-m-d')
          . sprintf(
                ' %02d:%02d:00',
                ($ampm == 'pm' ? ($hour % 12) + 12 : $hour % 12),
                $minute
            );

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

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