2

下面的代码片段显示了分期付款的模拟,具有固定的到期日期,每 30 天分配一次!

我想包括一个定期到期日期,例如每 20 天,或每 10 天 10 天,具体取决于变量$periodicity

我不知道该怎么做?

<?php
function calculate_due($num_installment, $first_due_date = null){
  if($first_due_date != null)
  {
    $first_due_date = explode('/',$first_due_date);
    $day = $first_due_date[0];
    $month = $first_due_date[1];
    $year = $first_due_date[2];
  }
  else
  {
    $day = date('d');
    $month = date('m');
    $year = date('Y');
  }
  
  $periodicity = 20;
 
  for($installment = 0; $installment < $num_installment; $installment++)
  {
      if ($periodicity == 30)
          echo date('d/m/Y', strtotime('+'.$installment. " month", mktime(0, 0, 0, $month, $day, $year))),'<br/>';
      else
          echo date('d/m/Y', strtotime('+'.$installment. " month", mktime(0, 0, 0, $month, $periodicity, $year))),'<br/>';
  }
}
 

echo 'Calculates installments from an informed date<br/>';
calculate_due(5, '10/10/2020');
4

1 回答 1

1

尝试这个,

<?php
function calculate_due($num_installment, $first_due_date = null, $days = 1){

    $start = DateTime::createFromFormat('d/m/Y', $first_due_date);
    
    $end = DateTime::createFromFormat('d/m/Y', $first_due_date);
    $end->add(new DateInterval('P'.($num_installment * $days).'D'));
    
    $period = new DatePeriod(
        $start,
        new DateInterval('P'.$days.'D'),
        $end
    );
    
    $return = [];
    foreach ($period as $date) {
       $return[] = $date->format('d/m/Y');    
    }
    return $return;
}
 
echo 'Calculates installments from an informed date<br/>'.PHP_EOL;

echo implode("\n", calculate_due(5, '10/10/2020', 20));

https://3v4l.org/TLR8a

更改20(最后一个函数参数)以适应之间的天数。

结果:

Calculates installments from an informed date<br/>
10/10/2020<br/>
30/10/2020<br/>
19/11/2020<br/>
09/12/2020<br/>
29/12/2020<br/>
于 2020-10-09T21:02:56.807 回答