计算2020-2-28下个月的时间规律,使用strtotime +1month后需要得到是2020-3-30

题目描述

选区_726.png
选区_727.png
选区_728.png

完整的对应时间

创建时间 过期时间 月数
2020-02-28 2020-03-30 1
2020-02-28 2020-04-29 2
2020-02-28 2020-05-30 3
2020-02-28 2020-06-29 4
2020-02-28 2020-07-29 5
2020-02-28 2020-08-29 6
2020-02-28 2020-09-28 7
2020-02-28 2020-10-29 8
2020-02-28 2020-11-28 9
2020-02-28 2020-12-29 10
2020-02-28 2021-01-28 11
2020-02-28 2021-02-27 12
2020-02-28 2021-03-30 13
2020-02-28 2021-04-29 14
2020-02-28 2021-05-30 15
2020-02-28 2021-06-29 16
2020-02-28 2022-02-27 24
2020-02-28 2023-02-27 36
2020-02-28 2024-02-27 48
2020-02-28 2025-02-26 60

题目来源及自己的思路

上面是接口返回的时间,在接口上post请求+1,则会延迟一个月时间.得到过期时间
如果我用如下代码

echo date("Y-m-d",strtotime("+1 month",strtotime("2020-02-28")));

则显示

2020-03-28

如果加+2则显示

echo date("Y-m-d",strtotime("+2 month",strtotime("2020-02-28")));
2020-04-28

如果加+12则显示

echo date("Y-m-d",strtotime("+12 month",strtotime("2020-02-28")));
2021-02-28

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

你期待的结果是什么?实际看到的错误信息又是什么?

如何才能实现如截图中返回的"过期时间",接口中计算的过期时间的规律又是什么

阅读 2.5k
2 个回答

将创建时间转换为时间戳,将时间戳加一个月的秒数,再计算出日期

先计算出每个自然月的天数,然后用起始时间加上天数

<?php
// 要加的月数
$month = 2;
$start = '2020-02-28';
$start = strtotime($start);
$month < 1 && $month = 1;
$days = 0;
for ($i = 1; $i <= $month; $i++) {
    $current = strtotime("first day of +${i}month", $start);
    $days += date('t', $current);
}

$end = strtotime("+$days days", $start);

echo date('Y-m-d', $end);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题