我想计算用户在特定持续时间内的平均时间,我有中每个时间的时间戳值。为了计算平均值,我想加上所有的时间戳,除以天数。但所有时间戳的总和给出了错误的输入,所以我想将时间戳转换为秒,这样我就可以将它们相加并计算平均值。我正在使用以下代码。
$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
提前谢谢。
你的问题不是很清楚,但我想我理解你想从一系列打卡时间中计算平均打卡时间。
日期对此没有好处,您需要为每个$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',
);
您所说的是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;
希望这能有所帮助!
尝试此代码
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;
}