Reputation: 586
I am writing a code to calculate the exact time elapsed between two points in time. This section of the code is supposed to calculate the number of minutes between years 2000 and 2019 (2000 and 2019 will be calculated individually due to the individual months, days etc...). The code is designed to compensate for leap years, however $total_minutes
remain 0 after I run the code.
$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;
}
}
How do I solve this problem?
Upvotes: 2
Views: 94
Reputation: 898
Here is another solution, you can check your minutes interval between two dates in a simple way:
<?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");
?>
I hope this helps.
Upvotes: 0
Reputation: 27723
These two methods might help you to calculate the total minutes in between two dates from two years, as you wish:
$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)
Upvotes: 1
Reputation: 4557
A simple way to get the number of minutes between the dates above would be to use 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}";
Upvotes: 1