php获取日期的月份,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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值