doufei7464 2014-12-05 05:28 采纳率: 0%
浏览 34

PHP相对月份未产生预期结果[重复]

This question already has an answer here:

So, I am working with subtracting relative months. According to the documentation:

Relative month values are calculated based on the length of months that they pass through. An example would be "+2 month 2011-11-30", which would produce "2012-01-30". This is due to November being 30 days in length, and December being 31 days in length, producing a total of 61 days.

I understand why the example when adding months, but I don't understand why 2014-12-31 -1 month produces 2014-12-01. Its 31 days in December, shouldn't the result be the last of November?

Example code. Function 1 produces the result I was expecting from function 2 and 3.

//Func 1
$date = '2014-12-31 23:59:59'; //YYYY-MM-DD
$days = 0;
echo $date.'<br>';
for ($i = 1; $i < 13; $i++) {
    $days += cal_days_in_month(CAL_GREGORIAN, (13-$i), 2014);
    echo date("Y-m-d H:i:s", strtotime("-$days days", strtotime($date))).'<br>';
}
echo "<br><br>";
//Func 2
$date = '2014-12-31 23:59:59'; //YYYY-MM-DD
echo $date.'<br>';
for ($i = 1; $i < 13; $i++) {
    echo date("Y-m-d H:i:s", strtotime("-$i months", strtotime($date))).'<br>';
}
//Func 3
echo "<br><br>";
$dateObj = new DateTime("2014-12-31 23:59:59");
echo $dateObj->format("Y-m-d H:i:s").'<br>';
$dateIntervalObj = new DateInterval("P1M");
for ($i = 0; $i < 12; $i++) {
    echo $dateObj->format("Y-m-d H:i:s").'<br>';
    $dateObj->sub($dateIntervalObj);
}

Result:

2014-12-31 23:59:59
2014-11-30 23:59:59
2014-10-31 23:59:59
2014-09-30 23:59:59
2014-08-31 23:59:59
2014-07-31 23:59:59
2014-06-30 23:59:59
2014-05-31 23:59:59
2014-04-30 23:59:59
2014-03-31 23:59:59
2014-02-28 23:59:59
2014-01-31 23:59:59
2013-12-31 23:59:59


2014-12-31 23:59:59
2014-12-01 23:59:59
2014-10-31 23:59:59
2014-10-01 23:59:59
2014-08-31 23:59:59
2014-07-31 23:59:59
2014-07-01 23:59:59
2014-05-31 23:59:59
2014-05-01 23:59:59
2014-03-31 23:59:59
2014-03-03 23:59:59
2014-01-31 23:59:59
2013-12-31 23:59:59


2014-12-31 23:59:59
2014-12-31 23:59:59
2014-12-01 23:59:59
2014-11-01 23:59:59
2014-10-01 23:59:59
2014-09-01 23:59:59
2014-08-01 23:59:59
2014-07-01 23:59:59
2014-06-01 23:59:59
2014-05-01 23:59:59
2014-04-01 23:59:59
2014-03-01 23:59:59
2014-02-01 23:59:59
</div>
  • 写回答

1条回答 默认 最新

  • dpv46227 2014-12-05 05:37
    关注

    seems to always round up:

    2014-10-31 +1 month => 2014-12-01    // this makes sense
    2014-12-31 -1 month => 2014-12-01    // this doesn't
    

    in both cases if the day does not exist, it uses the day after it.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大