duanquezhan7268 2013-11-27 18:13
浏览 40

几年,几个月和几周工作的数组,但一年的第01周显示不正确

I have an array of years, months and weeks.

//Returns an array containing the years, months and week numbers between two dates
function year_month($start_date, $end_date)
{
    $begin = new DateTime( $start_date );
    $end = new DateTime( $end_date);
    $end->add(new DateInterval('P1W')); //Add 1 week to include the end date as a week
    $interval = new DateInterval('P1W'); //Add 1 week
    $period = new DatePeriod($begin, $interval, $end);
    $aResult = array();
    foreach ( $period as $dt )
    {
        $aResult[$dt->format('Y')][$dt->format('M')][] = "W".$dt->format('W');
    }

    return $aResult;
}
echo '<pre>';
print_r(year_month("25-11-2013","26-01-2014"));
echo '</pre>';

it outputs the following:

   Array
 (
   [2013] => Array
    (
        [Nov] => Array
            (
                [0] => W48
            )

        [Dec] => Array
            (
                [0] => W49
                [1] => W50
                [2] => W51
                [3] => W52
                [4] => W01
            )

    )

[2014] => Array
    (
        [Jan] => Array
            (
                [0] => W02
                [1] => W03
                [2] => W04
                [3] => W05
            )

    )

)

Notice that w01 is in the Dec array instead of the January array. I assume this is because Monday is the start of each week and in this case Monday is the 30th of December. Any ideas on how to get around this? In fact I am not sure what to do with border cases in general. If a week starts in one month but ends in another it should not be inserted into both months I would rather it be in the month in which it ends. But not sure how to go about this.

  • 写回答

2条回答 默认 最新

  • dourong8495 2013-11-27 18:17
    关注

    Use the thursday in the week of the starting date as the starting point, before adding weeks. The thursday will always be in the correct month (since that's what we use to decide if we're going to have week 53 or week 1 in the last week of December). If that thursday is in January, you're going to get W1 and January, if it's in December, you're going to get W53 and December.

    If you want the month the week ends each time, use the sunday as the starting point instead.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算