计算从某个日期到 12 月的月份,然后计算从次年 1 月到同年 12 月的月份,然后是从 1 月到结束日期

时间:2021-05-23 17:24:01

标签: php mysql laravel

我的 start_date 为 1/10/2018,end_date 为 1/8/2020,这两个日期之间的月份差为 22,即 1 年 10 个月,现在,我想创建表每年年底终止如下:

表1 column_heading 将是“1/10/2018 - 31/12/2018” 该行将是“2个月”

表2 column_heading 将是“1/1/2019 - 31/12/2019” 并且该行将是“12 个月”

表3 column_heading 将是“1/1/2020 - 1/8/2020” 并且该行将是“8 个月”

我想循环某事,也许是日期之间的差异来创建必要的表数量,如果两个日期存在于同一年内,它只会创建 1 个表,如果进入下一年,则创建 2 个表,我使用 laravel 和 carbon 来操作日期。

感谢您的帮助。

像这样 enter image description here

1 个答案:

答案 0 :(得分:0)

这是一种方法。请注意,为了使用 PHP 日期函数,我必须将日期格式转换为 YYYY-mm-dd。最后你会得到一个数组,你可以很容易地将最终日期转换为你想要的格式。您可以在此处进行测试:https://www.tehplayground.com/lvuTdWl91TeItEQC

代码:

<?php
// example code

$s = "1/10/2018";
$e = "1/08/2020";

// reassemble so we can use the date functions YYYY-mm-dd
$s = implode("-", array_reverse(explode("/", $s)) );
$e = implode("-", array_reverse(explode("/", $e)) );
 
// get the parts separated
$start = explode("-",$s);
$end = explode("-",$e) ;

$iterations = ((intVal($end[0]) - intVal($start[0])) * 12) - (intVal($start[1]) - intVal($end[1])) ;

$sets=[$start[0] => array("start" => $s, "end" => "", "months" => 0)];
$curdstart= $curd = $s;
$curyear = date("Y", strtotime($s));

for($x=1; $x<=$iterations; $x++) {
    $curdend = date("Y-m-d", strtotime($curd . " +{$x} months"));
    $curyear = date("Y", strtotime($curdend));
    if (!isset($sets[$curyear])) {
        $sets[$curyear]= array("start" => $curdend, "end" => "", "months" => 0);
    }
    $sets[$curyear]['months']++;
    $sets[$curyear]['end'] = date("Y-m-", strtotime($curdend)) . "31";
    
}

die(print_r($sets,1));
$mctr = 0 ;

输出:

Array
(
    [2018] => Array
        (
            [start] => 2018-10-1
            [end] => 2018-12-31
            [months] => 2
        )

    [2019] => Array
        (
            [start] => 2019-01-01
            [end] => 2019-12-31
            [months] => 12
        )

    [2020] => Array
        (
            [start] => 2020-01-01
            [end] => 2020-08-31
            [months] => 8
        )

)