【问题标题】:PHP strtotime needs adjustmentPHP strtotime 需要调整
【发布时间】: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;

【问题讨论】:

标签: php wordpress strtotime


【解决方案1】:

正如strtotime 所说

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

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

在您的情况下,这两个时间都是相对于今天进行解释的,即今天早上 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');

【讨论】:

    猜你喜欢
    • 2011-09-11
    • 1970-01-01
    • 2011-08-10
    • 2012-09-18
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    相关资源
    最近更新 更多