【问题标题】:Need first and last day on a period datetime需要在一段时间日期时间的第一天和最后一天
【发布时间】:2020-02-13 13:46:39
【问题描述】:

我正在使用 Carbon Period 来获取两个日期之间的“N”天间隔。

在每个时期的迭代中,我需要知道如何获取每个时期的第一天和最后一天。

例如:

$period = CarbonPeriod::create('2019-10-01', '30 days', '2020-02-15');
// What I need is
// Period 1: from 2019-10-01 to 2019-10-31
// Period 2: from 2019-11-01 to 2019-11-30
// Period 3: from 2019-12-01 to 2019-12-31
// Period 4: from 2020-01-01 to 2020-01-31
// Period 5: from 2020-02-01 to 2020-02-15

【问题讨论】:

  • 在您查看文档后,仍然不清楚如何做到这一点? carbon.nesbot.com/docs/#api-period
  • 我当然读过文档。在开始日期和结束日期之间设置间隔很明显,但不知道如何从给定日期开始和结束日期的每个间隔中获取第一天和最后一天。

标签: php laravel datetime php-carbon


【解决方案1】:

首先你应该使用1 month 作为间隔而不是30 days

$period = CarbonPeriod::create('2019-10-01', '1 month', '2020-02-15');

然后你可以使用endOfMonth() 方法得到你预期的结果:

$dates = [];

foreach ($period as $index => $date) {
    $dates[] = sprintf("Period %s: from %s to %s",
        $index + 1,
        $date->toDateString(),
        $period->getEndDate()->min($date->endOfMonth())->toDateString()
    );
}

【讨论】:

    【解决方案2】:

    我认为您无法获取每个时期的开始/结束日期,但您可以使用复制/设置器来获取结束时期的第二天。

    $period = CarbonPeriod::create('2019-10-01', '30 days', '2020-02-15');
    $start = null;
    foreach($period as $key=>$date) {
        if(!$start) {
            echo "Start 1 : ".$period->getStartDate()->toDateString(). " End : ".$date->toDateString()."\n";
            $start = $date->copy()->addDay();
        } else {
            echo "Start 2 : ".$start->toDateString(). " End : ".$date->toDateString()."\n";
        }
        $start = $date->copy()->addDay();
    }
    if($start->lt($period->getEndDate())) {
        echo "Start : ".$start->toDateString(). " End : ".$period->getEndDate()->toDateString()."\n";
    }
    //Start : 2019-10-01 End : 2019-10-01
    //Start : 2019-10-02 End : 2019-10-31
    //Start : 2019-11-01 End : 2019-11-30
    //Start : 2019-12-01 End : 2019-12-30
    //Start : 2019-12-31 End : 2020-01-29
    //Start : 2020-01-30 End : 2020-02-15
    

    由于 2020-01-30 - 2020-02-15 不是 30 天,因此不会将其创建为另一个间隔。如果需要,您必须像最后几行一样手动检查是否添加它。

    【讨论】:

      猜你喜欢
      • 2015-01-31
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      相关资源
      最近更新 更多