【问题标题】:add days to month not exceeding last day of the month php添加天数不超过该月的最后一天php
【发布时间】:2016-04-15 06:59:41
【问题描述】:

我有这种形式的日期 - - 20160428000000(2016 年 4 月 28 日),即 yyyymmdd...

如果某些天(例如 3)被添加到这个日期,我需要它 - 它应该添加它们但不超过月份(04) - 预期输出 - 20160430000000 - 4 月 30 日

同样,20160226000000 + 5days 应该返回20160229000000,即闰年二月。这意味着它不应该跳到另一个月份。

任何提示/想法?

【问题讨论】:

  • 获取您的日期和该月最后一个日期之间的间隔。如果此间隔小于给定的添加间隔,则返回该月的最后一天。

标签: php date datetime


【解决方案1】:

另一种选择是使用DateTime 类来检查它:

首先当然是通过输入创建你的对象。然后,设置月份对象的结束日期。

之后,进行添加,然后检查它是否超过了结束日期。如果是,设置到最后,如果不是,则得到加法的结果:

$day = 5; // days to be added
$date = '20160226000000'; // input date
$dt = DateTime::createFromFormat('YmdHis', $date); // create the input date
$end = clone $dt; // clone / copy the input
$end->modify('last day of this month'); // and set it to last day
$dt->add(DateInterval::createFromDateString("+{$day} days")); // add x days
// make comparision
$final_date = ($dt > $end) ? $end->format('YmdHis') : $dt->format('YmdHis');
echo $final_date;

【讨论】:

  • 漂亮优雅! +1
  • 我正准备使用DateTimeImmutable 提出类似的建议,但它基本上是相同的逻辑。 +1 :)
  • 接受,因为它以我提到的相同形式返回日期。谢谢
  • @jitendrapurohit 很高兴这个帮助
【解决方案2】:

为此,您可以这样尝试:

$given_date = 20160428000000;
$no_of_day = 3;

if(date('m',strtotime($given_date)) < date('m',strtotime($given_date ." +".$no_of_day."days"))){
    echo "Exceeded to next month <br/>";
    echo "Last date of month should be: ".date("t M Y", strtotime($given_date));
}
else {
    echo "Next date will be after ".$no_of_day." day(s)<br/>";
    echo date('d M Y',strtotime($given_date ." +".$no_of_day."days"));
}

如果月份将跳转到下个月,那么它将显示当前月份的最后日期。 否则它将在延长天数后显示日期。

【讨论】:

  • 谢谢,但这会给我最后的日期 - 4 月 30 日吗?
  • @jitendrapurohit!会的,试试吧。
【解决方案3】:

如果添加的日期超过了最后一天,将选择最后一天作为新的日期。

<?php
$date_orig  = 20160226000000;
$add_day    = 5; # No. of days to add

$added_date      = strtotime($date_orig. ' + '.$add_day.' days'); // Add $add_day to $date_orig 
$last_date       = strtotime(date("YmtHis", strtotime($date_orig))); // Last day of $date_orig 
$new_date        = ($added_date > $last_date) ? $last_date : $added_date; // check the added date exceeds the last date
$new_date_format = date("YmdHis", $new_date); // Format Date

echo $new_date_format;
?>

【讨论】:

    【解决方案4】:
    <?php
        $month_end = date('t-m-Y'); // Gets the last day of the month; e.g 31-07-2019
        echo $month_end;
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-02
      • 2013-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-31
      • 1970-01-01
      相关资源
      最近更新 更多