如何使用php创建日期范围? [英] How to create a date range with php?

查看:81
本文介绍了如何使用php创建日期范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图花些时间用PHP。开始日期为2017年1月29日至2017年12月29日。但这发生在我2月份无法打印的情况下,因为该月份最多只有28天。无论如何,如何订购印刷品,但2月日期最多为28。

I tried to make time with PHP. start date of 2017-01-29 to 2017-12-29. But that happened I could not print in February because the month maximum of only 28 days. How to order printed anyway but with the February date up to 28.

我的脚本:

    date_default_timezone_set('UTC');

    // Start date
    $date = '2017-01-29';
    // End date
    $end_date = '2017-12-29';

    while (strtotime($date) <= strtotime($end_date)) {
                echo "$date\n"; 
                echo "<br>";
                $date = date ("Y-m-d", strtotime("+1 month", strtotime($date)));
    } 

输出:

推荐答案

使用DateTime类查找下个月的最后一天:

Use the DateTime class to find the last day of next month:

date_default_timezone_set('UTC');

// Start date
$date = '2017-01-29';
// End date
$end_date = '2017-12-29';

while (strtotime($date) <= strtotime($end_date)) {
            echo "$date\n"; 
            echo "<br>";
            $d = new DateTime( $date );
            $d->modify( 'last day of next month' );
            $date = $d->format( 'Y-m-d' );
}

现在,这可能并不是您完全感兴趣的,因为您可能想要尝试使用不同的开始日期,并且不将其延续到下个月的月底,或者您可能希望它使用2/28作为2月的日期,但随后每个连续的月回到29。但这应该使您更接近所需的逻辑。我认为使用DateTime将成为您答案的一部分。

Now this may not be fully what you're interested in since you might want to try different start dates and have it not go to the end of the next month or you might want it to use 2/28 for the February date, but then go back to the 29th for each successive month. But this should get you closer to the logic you are needing. I think using DateTime will be part of your answer.

这篇关于如何使用php创建日期范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆