1

我有以下代码,它显示了两个日期之间的差异。现在我想根据这个差额计算我的收入,基本费率为每小时 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";
4

4 回答 4

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; 
  } 
  //...
于 2013-03-24T17:16:26.660 回答
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);
于 2013-03-24T17:18:10.807 回答
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";
于 2013-03-24T17:18:38.383 回答
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; 
于 2013-03-24T17:20:03.377 回答