PHP中的时间记录计算

时间:2017-08-30 11:31:09

标签: php

我有一个充满时间记录的数据库表,我需要计算它们之间存在的小时数......

时间记录包含以下字段:'created'(即2017:08:30 11:15:00)和'direction'(即1代表"时钟输入"和& #34; 0"表示"时钟输出")。所以我需要设置一个开始和结束日期,然后选择该时间范围内的所有时间记录并计算工作小时数(direction=0direction=1的记录之间存在的小时数)

知道如何为此创建逻辑吗?结果必须是"小时"十进制格式(小数点后1位,即' 26.7'小时)。

我从建立变量开始:

$query_start_date = "2017-08-29 00:00:00";
$query_end_date = "2017-08-30 23:59:59";

假设这些是该时间范围内存在的时间记录:

time record 1: 'created'="2017-08-29 08:00:00", 'direction'=1;
time record 2: 'created'="2017-08-29 16:30:00", 'direction'=0;
time record 3: 'created'="2017-08-30 08:00:00", 'direction'=1;
time record 4: 'created'="2017-08-30 16:00:00", 'direction'=0;

但我不知道如何开始计算。我首先选择记录并将每个记录作为数组分配给变量吗?任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

将开始和结束时间分为两列:

$I->dontSeeInField($field, $value);

了解时差:

SELECT 
   created as start, 
   (select created from test t2 where t2.created > t.created
      and direction = 1 order by created limit 1) as end 
   FROM `test` t where direction = 0

最后计算总和:

select TIME_TO_SEC(TIMEDIFF(end, start))/60/60 as diff, start, end from
  (SELECT 
     created as start, 
     (select created from test t2 where 
        t2.created > t.created 
        and direction = 1 order by created limit 1) as end 
   FROM `test` t where direction = 0) intervals