我有以下代码,它显示了两个日期之间的区别。现在我想基于这个差异来计算我的收入,基本费率为每小时8美元,但我没有管理这样做,因为dateTime的方式让我回报差异。任何想法?
$lastUpdate = new DateTime($lastUpdate['lastUpdate']);
$currentTime = new DateTime("2013-03-24 19:45:55");
$interval = $lastUpdate->diff($currentTime);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days " . $interval->h . " hours " . $interval->i . " minutes " . $interval->s . " seconds";
答案 0 :(得分:2)
从差异中获取总秒数,将它们除以3600,然后将其除以费率。
尝试这样的事情:http://www.php.net/manual/en/dateinterval.format.php#102271
这里只是代码的一部分,可以给你一个想法:
//...
public function to_seconds()
{
return ($this->y * 365 * 24 * 60 * 60) +
($this->m * 30 * 24 * 60 * 60) +
($this->d * 24 * 60 * 60) +
($this->h * 60 * 60) +
($this->i * 60) +
$this->s;
}
//...
答案 1 :(得分:2)
解决方案是转换为秒并乘以8/3600
$lastUpdate = new DateTime($lastUpdate['lastUpdate']);
$currentTime = new DateTime("2013-03-24 19:45:55");
$interval = $lastUpdate->diff($currentTime);
//generate time string
$timeStr = "";
if($interval->y >0) { $timeStr .= $interval->y ." year" .($interval->y==1 ? " ": "s "); }
if($interval->m >0) { $timeStr .= $interval->m ." month" .($interval->m==1 ? " ": "s "); }
if($interval->d >0) { $timeStr .= $interval->d ." day" .($interval->d==1 ? " ": "s "); }
if($interval->h >0) { $timeStr .= $interval->h ." hour" .($interval->h==1 ? " ": "s "); }
if($interval->i >0) { $timeStr .= $interval->i ." minute" .($interval->i==1 ? " ": "s "); }
if($interval->s >0) { $timeStr .= $interval->s ." second" .($interval->s==1 ? " ": "s "); }
//add up all seconds
$seconds = ($interval->y * 365* 24 * 60 * 60)
+ ($interval->m * 30 * 24 * 60 * 60)
+ ($interval->d * 24 * 60 * 60)
+ ($interval->h * 60 * 60)
+ ($interval->i * 60)
+ $interval->s;
//multiply by your wage (in seconds)
$hourly_rate = 8.00;
$pay = ($seconds * $hourly_rate)/3600;
$pay = round($pay,2,PHP_ROUND_HALF_UP); //round to nearest cent
//print out the resulting time, rate & cost statement
printf("Total time of %sat hourly rate of $%.2f equates to $%.2f\n",$timeStr,$hourly_rate,$pay);
答案 2 :(得分:2)
为什么你不为你的目的使用strtotime
$lastUpdate = strtotime($lastUpdate['lastUpdate']);
$currentTime = strtotime("2013-03-24 19:45:55");
$interval = ($currentTime - $lastUpdate)/(3600);
$interval = round($interval,2);
$income = $interval*8;
echo $interval."hours";
答案 3 :(得分:1)
如果你想让输出很漂亮,你需要保留你所拥有的并计算一些新的变量。
$years = $interval->y * 365 / 24; // give it that it's not a leap year
$months = $interval->m * 730; // approximation of how many hours are in a month
// ... so on
$grandSummation = $years + $months + $days + $hours + $seconds;
$finalBaseApproximation = $grandSummation * 8;
echo "Your income is $" . $finalBaseApproximation;