计算每个用户两个时间戳之间的总时间

时间:2015-07-07 13:49:50

标签: php mysql

目前我遇到了一些MySQL查询。 我有一张这样的桌子:

ID|USERID|USERNAME|STARTTIME|ENDTIME|COMMITTYPE

用户单击前端中的按钮 - >开始< - 和 - >停止< - 。 这将创建一个具有各自职责,开始时间和结束时间的数据库条目。因此,每次单击开始都会在数据库中创建一个新的行/条目,并通过单击停止按钮来完成。

我的问题是,是否有机会计算每个用户的开始时间和结束时间与提交类型之间的总时间?

3 个答案:

答案 0 :(得分:2)

这可能有效

SELECT USERID, COMMITTYPE, MIN(STARTTIME), MAX(ENDTIME), 
SUM(TIME_TO_SEC(TIME_DIFF(ENDTIME - STARTTIME))/3600) hours FROM tablename
GROUP BY USERID, COMMITTYPE

答案 1 :(得分:1)

你指的是这样的东西吗?

SELECT COMMITTYPE, USER, (ENDTIME - STARTTIME) AS ELLAPSED_TIME
FROM YOUR_TABLE GROUP BY COMMITTYPE, USERID;

答案 2 :(得分:0)

SELECT DATEDIFF('new_date', 'old_date');

// eg

SELECT DATEDIFF('2006-04-01','2006-04-01');

IG使用LINUX

<?php

  // Set timezone
  date_default_timezone_set("UTC");

  // Time format is UNIX timestamp or
  // PHP strtotime compatible strings
  function dateDiff($time1, $time2, $precision = 6) {
    // If not numeric then convert texts to unix timestamps
    if (!is_int($time1)) {
      $time1 = strtotime($time1);
    }
    if (!is_int($time2)) {
      $time2 = strtotime($time2);
    }

    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2) {
      $ttime = $time1;
      $time1 = $time2;
      $time2 = $ttime;
    }

    // Set up intervals and diffs arrays
    $intervals = array('year','month','day','hour','minute','second');
    $diffs = array();

    // Loop thru all intervals
    foreach ($intervals as $interval) {
      // Create temp time from time1 and interval
      $ttime = strtotime('+1 ' . $interval, $time1);
      // Set initial values
      $add = 1;
      $looped = 0;
      // Loop until temp time is smaller than time2
      while ($time2 >= $ttime) {
        // Create new temp time from time1 and interval
        $add++;
        $ttime = strtotime("+" . $add . " " . $interval, $time1);
        $looped++;
      }

      $time1 = strtotime("+" . $looped . " " . $interval, $time1);
      $diffs[$interval] = $looped;
    }

    $count = 0;
    $times = array();
    // Loop thru all diffs
    foreach ($diffs as $interval => $value) {
      // Break if we have needed precission
      if ($count >= $precision) {
 break;
      }
      // Add value and interval 
      // if value is bigger than 0
      if ($value > 0) {
 // Add s if value is not 1
 if ($value != 1) {
   $interval .= "s";
 }
 // Add value and interval to times array
 $times[] = $value . " " . $interval;
 $count++;
      }
    }

    // Return string with times
    return implode(", ", $times);
  }

?>

///

echo dateDiff("2010-01-26", "2004-01-26") . "\n";
echo dateDiff("2006-04-12 12:30:00", "1987-04-12 12:30:01") . "\n";
echo dateDiff("now", "now +2 months") . "\n";
echo dateDiff("now", "now -6 year -2 months -10 days") . "\n";
echo dateDiff("2009-01-26", "2004-01-26 15:38:11") . "\n";

<强>输出

  

6年   18年,11个月,30天,23小时,59分59秒2   月6年,2个月,10天4年,11个月,30天,8   小时21分49秒