【问题标题】:php calculate the number of months for invoice delay between two datesphp计算两个日期之间发票延迟的月数
【发布时间】:2021-02-11 06:51:13
【问题描述】:

好的,我想弄清楚如何创建函数来获取两个日期之间发票延迟的月数。我尝试了很多小时,但没有成功,我很困惑从哪里开始......

公式如下:

从:1/1/2020 到:10-02-2021

Months 1, 2, 3, 4, 5 (if not paid during this months, we count the number of month starting from the next month.)
count the number of months from the next month, from 6-2020 to 02-2021
result 9;

同样,我们也这样做:

Months: 4, 5, 6, 7, 8
count the number of months from the next month, from 9-2020 to 02-2021
result 6;

7, 8, 9, 10, 11
count the number of months from the next month, from 12-2020 to 02-2021
result 3;

10, 11, 12, 01, 02
count the number of months from the next month, from 3-2021 to 02-2021 (not possible since date end in 10-02-2021
result 0;

所以,最后我们计算月数:

9 + 6 + 3 + 0 = 18

函数应该打印“18”。

提前致谢!

【问题讨论】:

标签: php


【解决方案1】:

不确定这个逻辑是否能达到您想要的结果并且是否足够健壮,但这里可以。

您可以在函数中使用$results 数组的结果来计算价格。

<?php
$start = '2020-01-01';
$end = '2021-02-10';

$diff = monthDiff($start, $end) + 1; // OP uses 14 - counts 10 days feb as 1 month.
$offset = 5; // 5 months +15%
while($diff >= $offset) {
    $result[] = $diff - $offset;
    $offset += 3;
}


// source: https://stackoverflow.com/questions/13416894/calculate-the-number-of-months-between-two-dates-in-php
function monthDiff($start, $end)
{
    $ts1 = strtotime($start);
    $ts2 = strtotime($end);

    $year1 = date('Y', $ts1);
    $year2 = date('Y', $ts2);

    $month1 = date('m', $ts1);
    $month2 = date('m', $ts2);

    $diff = (($year2 - $year1) * 12) + ($month2 - $month1);
    return $diff;
}

$result:

array (size=4)
  0 => int 9
  1 => int 6
  2 => int 3
  3 => int 0

echo array_sum($result); // 18

demo

【讨论】:

  • 谢谢,我会尝试另一个日期并告诉你是否有效,还有为什么不够健壮,我认为虽然很慢,顺便说一句,请问有没有办法在 excel 中制作它?
猜你喜欢
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
  • 2021-07-20
  • 2019-06-07
  • 1970-01-01
  • 2010-12-04
  • 2022-11-18
相关资源
最近更新 更多