PHP number of days for each year between two dates

If you're a new user of AppGini, feel free to ask general usage questions, or look for answers here.
Post Reply
G Belgrado
Veteran Member
Posts: 61
Joined: 2017-03-12 09:24

PHP number of days for each year between two dates

Post by G Belgrado » 2023-10-10 09:07

PHP
how to calculate interest by number of days with a different rate for each year, example:
start date 2021-05-12
end date 2023-09-24
interest rate:
(a) 2021 = 3.50%
(b) 2022 = 2.94%
(c) 2023 = 4.87%
progress:
days to calculate:
from 2021-05-12 (start) to 2021-12-31 = x
from 2022-01-01 to 2022-12-31 = y
from 2023-01-01 to 2023-09-24 (end) = z

pd1 = (a / 365) * x
pd2 = (b / 365) * y
pd3 = (c / 365) * z

total interest = (pd1 + pd2 + pd3)

in PHP
anyone want to help me?
(forgive me, I'm a 62 year old idiot)
many thanks

pbottcher
AppGini Super Hero
AppGini Super Hero
Posts: 1709
Joined: 2018-04-01 10:12

Re: PHP number of days for each year between two dates

Post by pbottcher » 2023-10-10 21:04

Hi, as you ask for a php solution you could try:

Code: Select all

// Define start and end dates

$startdate='2021-05-12';
$enddate='2023-09-24';

$start_date = new DateTime($startdate);
$end_date = new DateTime($enddate);

// Define interest rates for each year
$interest_rates = [
    2021 => 3.50,
    2022 => 2.94,
    2023 => 4.87
];

// Initialize total interest
$total_interest = 0;

// Calculate interest for each year
foreach ($interest_rates as $year => $rate) {
    // Calculate the number of days in the year
    $year_start = new DateTime("$year-01-01");
    $year_end = new DateTime("$year-12-31");
    if ($year == $start_date->format('Y')) {
        $year_start = max($year_start, $start_date);
        $year_end = min($year_end, new DateTime("$year-12-31"));
    } elseif ($year == $end_date->format('Y')) {
        $year_start = max($year_start, new DateTime("$year-01-01"));
        $year_end = min($year_end, $end_date);
    }
    $interval = $year_start->diff($year_end);
    $days_in_year = $interval->days + 1;

    // Calculate interest for the year and add it to the total
    $year_interest = ($rate / 365) * $days_in_year;
    $total_interest += $year_interest;
}

// Display the total interest
echo "Total interest: $total_interest";  // maybe you want to round the result
Any help offered comes with the best of intentions. Use it at your own risk. In any case, please make a backup of your existing environment before applying any changes.

G Belgrado
Veteran Member
Posts: 61
Joined: 2017-03-12 09:24

Re: PHP number of days for each year between two dates

Post by G Belgrado » 2023-10-11 06:55

Hi, I tried it, it works perfectly
thank you for your availability, pböttcher

Post Reply