【发布时间】:2012-04-08 04:40:31
【问题描述】:
我有一个在线表单,其中包含一些包含时间数据的字段。我将此数据存储到 MySQL 数据库中的 time 字段中,该字段需要格式为 hh:mm:ss。如果用户正确输入了这种格式的时间,那么我想接受数据。我还希望允许用户输入标准美国时间的时间,例如9:30 am 或11:25 pm 或10:27 am 等。
基本上我想首先测试时间是否采用正确的数据库格式(hh:mm:ss),如果不是,则测试它是否采用第二种可接受的格式(hh:mm am/pm),如果是,然后我将使用 PHP 函数strtotime() 将其转换为数据库时间格式。如果它不是这两种格式,那么我们会显示一条错误消息并死掉。
有谁知道如何测试变量的值是否与这些时间格式之一匹配?
我想做的伪PHP代码:
<?php
$value = //some time;
if (is_database_time($value)){
// good no problem
}else if (is_usa_time($value)){
$value = strtotime($value);
}else{
die("error incorrect time format, try again.");
}
?>
** 编辑 **
感谢大家的帮助。我在这里使用了一些信息来制作一个完美运行的功能:
<?php
function filter_time($key,$value){
// this section handles the storage of time data
if (preg_match('/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)){
//do nothing
}else if (preg_match('/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i', $value)){
$value = date( 'H:i:s', strtotime($value));
}else{
display_error('incorrect time format in '.$key.' field.');
}
return $value;
}
?>
【问题讨论】:
-
为什么要强制用户输入特定格式?您已经在使用 strtotime()。
-
你必须提供特定格式的strtotime,不是任何任意格式都可以。
-
正如@PenguinCoder 所指出的,strtotime() 几乎可以理解用户输入的任何格式。为什么不尝试转换,如果有任何不确定性,向用户展示结果是什么?
-
感谢您的建议,这是一种方法。
-
我建议对这两种正确的格式使用
date('H:i:s', strtotime($value)),以确保您的输出$value在hh部分中具有前导零。请参阅我的更新仅供参考。
标签: php testing time datetime-format time-format