2016-11-13 49 views
0

我正在开发一个php函数来计算wordpress forms插件中两个用户输入时间字段之间的总时间,但是当时间跨越2400小时时该函数不工作。PHP strtotime需要调整

下面是确切的情况:我试图计算用户睡了多久,但当开始时间在晚上(例如23:00)和结束时间(唤醒)时,我得到一个负数第二天早上(例如07:00) - 这是因为时间是从同一天显示两次的表单中获取的,所以开始时间显示为大于使用时间换算的结束时间。

这里是原代码:

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; 
} 

这里是我试图通过添加12小时到结束的时间来调整,如果它是小于开始时间:

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; 
+7

使用完整日期\时间 – 2016-11-13 20:13:06

+1

https://secure.php.net/DateTime –

回答

0

由于strtotime声明

int strtotime (string $time [, int $now = time() ]) 

乐趣ction希望给出一个包含英文日期格式的字符串,并且将尝试将该格式解析为Unix时间戳(自1970年1月1日00:00:00以来的秒数),(相对于现在给出的时间戳),或者如果现在没有提供当前时间。

在你的情况下,这两个时间都是相对于今天,也就是今早7点和晚上11点。

要解决这个问题,只需调整一整天, 24*60*60秒,或者给明天的日期作为结束的基础。因此,而不是两个大的分支,必须在开始进行小的调整,然后计算差值均匀

$start = strtotime($_POST['item_meta'][88]); 
$end = strtotime($_POST['item_meta'][78]); 
if ($end < $start) 
    $end += 86400; // shift the end 24 hours into tomorrow 

$totaltime = $end - $start; 

无关,但你并不需要手动计算小时和分钟,使用DateTime::format代替

$date = DateTime::createFromFormat('U', $totaltime); 
$s = $date->format('H:I'); 
+0

感谢Olaf!比我最初的尝试更优雅... – AFSoar01