【发布时间】:2016-11-13 20:12:03
【问题描述】:
我正在开发一个 php 函数来计算来自 wordpress 表单插件的两个用户输入时间字段之间的总时间,但是当时间超过 2400 小时时,该函数不起作用。
这是确切的情况:我正在尝试计算用户睡了多长时间,但是当开始时间是晚上(例如 23:00)和结束时间(醒来)时我得到一个负数第二天早上(例如 07:00) - 这是因为时间取自显示同一天两个时间的表单,因此使用 strtotime 转换时,开始时间看起来大于结束时间。
这是原始代码:
add_filter('frm_validate_field_entry', 'calculate_time', 11, 3);
function calculate_time($errors, $field, $value){
if($field->id == 98){ //98 is the field id from the wordpress plugin that will store the total time I'm using
$start = (strtotime($_POST['item_meta'][88])); //88 is the field id for 'go to sleep time' from the wordpress forms program - the user selects times from 00:00 to 23:00
$end = (strtotime($_POST['item_meta'][78])); //78 is the field id for 'wake up time' from the wordpress forms program - the user selects times from 00:00 to 23:00
$totaltime = ($end - $start);
$hours = intval($totaltime / 3600);
$seconds_remain = ($totaltime - ($hours * 3600));
$minutes = intval($seconds_remain / 60);
$totaltime = $hours . ':' . $minutes;
$value = $_POST['item_meta'][98] = $totaltime; //change 25 to the ID of the hidden or admin only field which will hold the calculation
}
return $errors;
}
如果结束时间小于开始时间,我尝试通过以下方式调整结束时间:
add_filter('frm_validate_field_entry', 'calculate_time', 11, 3);
function calculate_time($errors, $field, $value){
if($field->id == 98){
$start = (strtotime($_POST['item_meta'][88]));
$end = (strtotime($_POST['item_meta'][78]));
if ($end < $start) {
$end = ($end + 43200)
$totaltime = ($end - $start);
$hours = intval($totaltime / 3600);
$seconds_remain = ($totaltime - ($hours * 3600));
$minutes = intval($seconds_remain / 60);
$totaltime = $hours . ':' . $minutes;
$value = $_POST['item_meta'][98] = $totaltime;
} else
{
$totaltime = ($end - $start);
$hours = intval($totaltime / 3600);
$seconds_remain = ($totaltime - ($hours * 3600));
$minutes = intval($seconds_remain / 60);
$totaltime = $hours . ':' . $minutes;
$value = $_POST['item_meta'][98] = $totaltime;
}
}
return $errors;
【问题讨论】:
-
使用完整的日期\时间