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

时间:2018-06-11 15:25:00

标签: php laravel php-carbon

我有一个碳实例

   $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 {
     "date": "2018-07-11 10:00:00",
     "timezone_type": 3,
     "timezone": "Europe/Vienna",
   }

我知道解决方案涉及将其转换为时间戳或Datetime类,如此

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

这是我目前使用的,但我正在寻找更多"愚蠢的"我通过official site进行搜索,但无法找到任何内容,因此需要一些帮助。

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

2 个答案:

答案 0 :(得分:4)

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

$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

答案 1 :(得分:1)

请参阅文档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));