如何在 Carbon 实例中添加 CarbonInterval 实例

How to add CarbonInterval instance in Carbon instance

我有一个碳实例

   $a = Carbon\Carbon::now();

   Carbon\Carbon {
     "date": "2018-06-11 10:00:00",
     "timezone_type": 3,
     "timezone": "Europe/Vienna",
   }

和一个 CarbonInterval 实例

   $b = CarbonInterval::make('1month');


     Carbon\CarbonInterval {
     "y": 0,
     "m": 1,
     "d": 0,
     "h": 0,
     "i": 0,
     "s": 0,
     "f": 0.0,
     "weekday": 0,
     "weekday_behavior": 0,
     "first_last_day_of": 0,
     "invert": 0,
     "days": false,
     "special_type": 0,
     "special_amount": 0,
     "have_weekday_relative": 0,
     "have_special_relative": 0,
   }

如何在 carbon 实例中添加间隔以便我得到

   Carbon\Carbon {
     "date": "2018-07-11 10:00:00",
     "timezone_type": 3,
     "timezone": "Europe/Vienna",
   }

我知道涉及将其转换为时间戳或日期时间的解决方案 class 像这样

strtotime( date('Y-m-d H:i:s', strtotime("+1 month", $a->timestamp ) ) );  

这是我目前正在使用的,但我正在寻找更 "carbony" 的方式,我在 official site 中进行了搜索,但找不到任何相关信息,因此需要一些帮助。

更新: 只是为了给你上下文 在前端我有两个控件第一个是间隔(天,月,年)第二个是文本框所以根据组合我动态生成字符串,如“2 days”,“3 months" 等等然后获取间隔 classes

查看文档 https://carbon.nesbot.com/docs/#api-addsub

$carbon = Carbon\Carbon::now();
$monthLater = clone $carbon;
$monthLater->addMonth(1);
dd($carbon, $monthLater);

结果是

Carbon {#416 ▼
  +"date": "2018-06-11 16:00:48.127648"
  +"timezone_type": 3
  +"timezone": "UTC"
}

Carbon {#418 ▼
  +"date": "2018-07-11 16:00:48.127648"
  +"timezone_type": 3
  +"timezone": "UTC"
}

对于此间隔 [月、世纪、年、季度、天、工作日、周、小时、分钟、秒],您可以使用

$count = 1; // for example
$intrvalType = 'months'; // for example
$addInterval = 'add' . ucfirst($intrvalType);
$subInterval = 'sub' . ucfirst($intrvalType);
$carbon = Carbon\Carbon::now();
dd($carbon->{$addInterval}($count));
dd($carbon->{$subInterval}($count));

我不知道添加间隔的内置函数,但应该起作用的是将间隔的总秒数添加到日期:

$date = Carbon::now(); // 2018-06-11 17:54:34
$interval = CarbonInterval::make('1hour');

$laterThisDay = $date->addSeconds($interval->totalSeconds); // 2018-06-11 18:54:34

编辑:找到更简单的方法!

$date = Carbon::now(); // 2018-06-11 17:54:34
$interval = CarbonInterval::make('1hour');

$laterThisDay = $date->add($interval); // 2018-06-11 18:54:34

之所以有效,是因为 Carbon 基于 DateTimeCarbonInterval 基于 DateInterval。参见 here 方法参考。