繁体   English   中英

添加天数不超过一个月的最后一天php

[英]add days to month not exceeding last day of the month php

我有这个表格的日期 - - 20160428000000 (2016年4月28日)即yyyymmdd ...

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

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

任何提示/想法?

另一种方法是使用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;

为此你可以尝试这样:

$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"));
}

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

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

<?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;
?>
<?php
    $month_end = date('t-m-Y'); // Gets the last day of the month; e.g 31-07-2019
    echo $month_end;
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM