简体   繁体   English

用 PHP Carbon 接收下个月的最后一天

[英]Receiving the last day of the next month with PHP Carbon

If the date is the last day of the month, I want to get the last day of the next month.如果日期是该月的最后一天,我想获得下个月的最后一天。 I don't want the time to change.我不想改变时间。

Original date -> 2022-31-01 14:00:00
I need        -> 2022-28-02 14:00:00

Original date -> 2022-28-02 14:00:00
I need        -> 2022-31-03 14:00:00
  • $date->lastOfMonth() returns the last day of $date 's month. $date->lastOfMonth()返回$date月份的最后一天。
  • $date->isLastOfMonth() returns true if $date is the last day of the month.如果$date是该月的最后一天,则 $ $date->isLastOfMonth()返回 true。

Assuming $date is a Carbon instance, then it's just a matter of using a few functions and a ternary operator.假设$date是一个Carbon实例,那么它只是使用一些函数和一个三元运算符的问题。

$result = $date->isLastOfMonth()
    ? $date->addDays(1)->lastOfMonth()
    : $date;

To keep the time part of the date, you'll need to create an interval first and add it later.要保留日期的时间部分,您需要先创建一个间隔,然后再添加。

$interval = $date->diffAsCarbonInterval($date->startOfDay());

$result = $date->isLastOfMonth()
    ? $date->addDays(1)->lastOfMonth()->add($interval)
    : $date;

@IGP answer's is correct, but; @IGP 的回答是正确的,但是;

$date->startOfDay() -> changes your original date. $date->startOfDay() -> 更改您的原始日期。

you should use $date->copy()->startOfDay()你应该使用$date->copy()->startOfDay()

Carbon is an extension of DateTime. Carbon 是 DateTime 的扩展。 However, Carbon is not needed here as there is a very simple solution using DateTime.但是,这里不需要 Carbon,因为有一个使用 DateTime 的非常简单的解决方案。 It only has to be checked whether the day of the date (d) matches the last day of the month (t).只需检查日期 (d) 的日期是否与月份的最后一天 (t) 匹配。 if so, then it is modified to the last day of the next month.如果是,则修改为下个月的最后一天。 Time remains unaffected.时间不受影响。

$dt = new DateTime('2022-01-31 14:00:00');

if($dt->format('d') == $dt->format('t')){
  $dt->modify('last Day of next month');
}

//test output
echo $dt->format('Y-m-d H:i:s')."\n";

Try self .尝试自我

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

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