我正在编写代码以计算两个时间点之间经过的确切时间。代码的此部分应该计算2000年至2019年之间的分钟数(由于各个月,日等原因,将分别计算2000年和2019年)。该代码旨在补偿leap年,但是在运行代码后$total_minutes
仍为0。
$years_1 = 2000;
$years_2 = 2019;
$years = $years_2 - $years_1;
$total_minutes = 0;
$n = $years - 2;
$start_year = $years_1 + 1;
for ($year = $start_year; $year <= $n; $year++) {
if ((($year % 4 == 0) && ($year % 100 != 0)) || ($year % 400 == 0)) {
$total_minutes += 527040;
} else {
$total_minutes += 525600;
}
}
如何解决此问题?
答案 0 :(得分:2)
获取上述日期之间的分钟数的一种简单方法是使用PHP strtotime()
:
// You could also pass in datestamps if needed.
// ie: strtotime('2019-03-12 22:44:22')
$seconds = strtotime('first day of january 2019')-strtotime('first day of january 2010');
$minutes = number_format($seconds/60,2);
echo "Minutes: {$minutes}";
答案 1 :(得分:1)
这两种方法可能会帮助您根据需要计算两年中两个日期之间的总分钟数:
$year2_date = new DateTime('2000-01-01 00:00:00');
$year1_date = $year2_date->diff(new DateTime('2019-12-12 00:00:00'));
$total_minutes = $year1_date->days * 24 * 60;
$total_minutes += $year1_date->h * 60;
$total_minutes += $year1_date->i;
var_dump($total_minutes);
$year2_date = strtotime('2000-01-01 00:00:00');
$year1_date = strtotime('2019-12-12 00:00:00');
$total_minutes = abs($year2_date - $year1_date) / 60;
var_dump($total_minutes);
int(10490400)
答案 2 :(得分:0)
这是另一种解决方案,您可以通过一种简单的方法来检查两个日期之间的分钟间隔:
<?php
function Calc_Minutes($day1, $day2) {
date_default_timezone_set('Europe/Rome');
$date1 = new DateTime($day1);
$date1->format('Y-m-d H:i:s');
$date2 = new DateTime($day2);
$date2->format('Y-m-d H:i:s');
$diffs = $date2->diff($date1);
$minutes = ($diffs->days * 24 * 60) + ($diffs->h * 60) + $diffs->i;
return $minutes;
}
echo Calc_Minutes("2000-01-01 00:00:00", "2019-01-01 00:00:00");
?>
我希望这会有所帮助。