我想计算特定持续时间内用户的平均时间,我有每个时间的时间戳值。 要计算平均值,我想添加所有时间戳并除以天数。 但所有时间戳的总和给出了错误的输入,所以我想将时间戳转换为秒,以便我可以添加它们并计算平均值。 我正在使用以下代码。
$timeInTotalSec = 0;
$timeInTotalSec += intval(date("H",$punchintime)) * 60 * 60;
$timeInTotalSec += intval(date("i",$punchintime)) * 60;
$timeInTotalSec += intval(date("s",$punchintime));`
但
date("H",$punchintime)
给了我适当的价值但是
intval(date("H",$punchintime))
给我 0
提前致谢。
答案 0 :(得分:1)
你所说的是unixtime。 Unixtime是unix时代(1970年1月1日)的秒数。要在两个时间戳中获得不同的时间,您可以简单地减去第二个时间戳的第一个时间戳。
$timestamp1 = date('U');
然后一段时间后:
$timestamp2 = date('U');
存储这些变量,何时需要获得差异:
$difference = $timestamp2 - $timestamp1;
然后,您可以使用基本数学格式化时间:
$seconds = $difference;
$minutes = $seconds/60;
$hours = $minutes/60;
$days = $hours/24;
希望这有帮助!
答案 1 :(得分:1)
你的问题不是很清楚,但我想我明白你想要计算一系列时间的平均时间。
日期对此无益,您需要隔离每个$punchintime
午夜后的秒数并计算其平均值。以下代码执行此操作。我创建了一系列时间来说明我的观点,我对你的系统一无所知,所以生成输入数组归你所有。
$punchInTimes = array(
'2013-08-01 09:00',
'2013-08-02 09:06',
'2013-08-03 08:50',
'2013-08-04 09:20',
'2013-08-05 09:01',
'2013-08-06 08:56',
);
function getAverageTime(array $times)
{
$seconds = $average = 0;
$result = null;
//get seconds after midnight
foreach($times as $dateString){
$date = new \DateTime($dateString);
list($datePart) = explode(' ', $dateString);
$midnight = new \DateTime($datePart);
$seconds += $date->getTimestamp() - $midnight->getTimestamp();
}
if($seconds > 0){
$average = $seconds/count($times);
$hours = floor($average/3600);
$average -= ($hours * 3600);
$minutes = floor($average/60);
$average -= ($minutes * 60);
$result = new \DateInterval("PT{$hours}H{$minutes}M{$average}S");
} else $result = new \DateInterval('PT0S');
return $result->format("%Hh %Mm %Ss");
}
echo "Average clock in time is " . getAverageTime($punchInTimes);
<强>输出: - 强>
平均时钟是09h 00m 10s
这对于跨越午夜的时间不起作用,例如像这样的数组: -
$aroundMidnight = array(
'2013-08-01 23:59',
'2013-08-02 00:02',
);
答案 2 :(得分:0)
试试这段代码
public static function sec2hms($sec, $padHours = false) {
// start with a blank string
$hms = "";
// do the hours first: there are 3600 seconds in an hour, so if we divide
// the total number of seconds by 3600 and throw away the remainder, we're
// left with the number of hours in those seconds
$hours = intval(intval($sec) / 3600);
// add hours to $hms (with a leading 0 if asked for)
$hms .= ($padHours) ? str_pad($hours, 2, "0", STR_PAD_LEFT) . ":" : $hours . ":";
// dividing the total seconds by 60 will give us the number of minutes
// in total, but we're interested in *minutes past the hour* and to get
// this, we have to divide by 60 again and then use the remainder
$minutes = intval(($sec / 60) % 60);
// add minutes to $hms (with a leading 0 if needed)
$hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT) . ":";
// seconds past the minute are found by dividing the total number of seconds
// by 60 and using the remainder
$seconds = intval($sec % 60);
// add seconds to $hms (with a leading 0 if needed)
$hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);
// done!
return $hms;
}