0

我正在计算两个日期之间的月、日、小时和分钟,我已经成功地计算出月、日和分钟,但我不能让它计算出分钟,下面是我的代码.

<?php
    $date1 = "2012-07-01 00:00:00";
    $date2 = "2012-09-30 00:00:00";

    $diff = abs(strtotime($date2) - strtotime($date1));

    $years = floor($diff / (365*60*60*24));
    $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
    $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
    $minutes = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24) / (60*60*24) / (60*60));

    printf("%d years, %d months, %d days, %d minutes\n", $years, $months, $days, $minutes);

?>
4

3 回答 3

1

在解决其他所有问题时尝试减少$diff变量:

$years = floor($diff / 31557600); // 31557600 = 365.25 * 86400
$diff -= $years * 31557600;
// I'd skip months, since different months have a different number of days.
// If you *really* want it, calculate the number of months from the days below.
$days = floor($diff / 86400); // 86400 = 24 * 3600
$diff -= $days * 86400;
$hours = floor($diff / 3600); // 3600 = 60 * 60
$diff -= $days * 3600;
$minutes = floor($diff / 60);
$diff -= $minutes * 60;
// $diff now equals the number of seconds left over

或者,查看 PHP 的日期/时间对象

$date1 = new DateTime("2012-07-01 00:00:00");
$date2 = new DateTime("2012-09-30 00:00:00");
$diff = $date1->diff($date2); // $diff is a DateInterval object

查看DateInterval->format()以确定如何格式化输出$diff

于 2012-06-22T16:26:47.640 回答
1

解决这个问题的最好和最准确的方法是使用DateTime类。否则,当您处理日期异常(闰年等)时,您会遇到问题。

$format = 'Y-m-d h:i:s';
$tz = new DateTimeZone('America/New_York');

// Create DateTime objs based on the above format
$t1 = DateTime::createFromFormat( $format, "2012-07-01 00:00:00", $tz);
$t2 = DateTime::createFromFormat( $format, "2012-09-30 00:00:00", $tz);

// Find the difference between them
$diff = $t1->diff( $t2);

// Print out the difference in each amount
$outputs = array( 'Y' => 'Year', 'm' => 'Month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'seconds');

foreach( $outputs as $key => $value)
    echo $diff->format( '%'.$key) . ' ' . $value . "\n";

输出

00 Year
2 Month
29 day
0 hour
0 minute
0 seconds
于 2012-06-22T16:29:59.733 回答
0

曾经具有以下功能之一,将秒转换为天/周/hh:mm:ss 时间等。这应该回答您的查询。

function duration ($sec, $padHours = false)  {
  if ($sec > 1209600) return "> ". intval(intval($sec) / 604800) . " weeks";
  if ($sec > 604800) return "1 week";
  if ($sec > 172800) return "> ". intval(intval($sec) / 86400) . " days";
  if ($sec > 86400) return "1 day";
  $hms = "";
  $hours = intval(intval($sec) / 3600);
  $hms .= ($padHours)
        ? str_pad($hours, 2, "0", STR_PAD_LEFT). ":"
        : $hours. ":";
  $minutes = intval(($sec / 60) % 60);
  $hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ":";
  $seconds = intval($sec % 60);
  $hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);
  return $hms;

}
于 2012-06-22T16:23:56.633 回答