PHP获取两个日期之间的月份

获取两个日期之间的月份

$s = '2019-02-05';
$e = '2019-07-20';

 

$start    = new DateTime($s);
$end      = new DateTime($e);
// 时间间距 这里设置的是一个月
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
    echo $dt->format("Y-m") . "
n"; }

输出结果:

2019-03
2019-04
2019-05
2019-06

 

扩展知识

$s = '2019-02-05';
$e = '2019-07-20';
// 获取首月的月初和月末日期
if (date('j', strtotime($s)) > 1) {
    $start_day_head = date('Y-m-01', strtotime($s));
    $end_day_head = date('Y-m-t', strtotime($s));
    $s = date('Y-m-01', strtotime("+1 months", strtotime($s)));
}
// 获取末月的月初和月末日期
if (date('j', strtotime($e)) > 1) {
    $start_day_tail = date('Y-m-01', strtotime($e));
    $end_day_tail = date('Y-m-t', strtotime($e));
    $e = date('Y-m-t', strtotime("-1 months", strtotime($e)));
}

输出:

2019-02-01
2019-02-28
2019-03-01
2019-07-01
2019-07-31
2019-06-30

DateTime 类

温馨提示: 本文最后更新于2024-12-31 21:00:34,某些文章具有时效性,若有错误或已失效,请在下方 留言或联系 蚂蚁官方
© 版权声明
THE END
喜欢就支持一下吧
点赞6赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容