我有一个碳实例
$a = CarbonCarbon::now();
CarbonCarbon {
"date": "2018-06-11 10:00:00",
"timezone_type": 3,
"timezone": "Europe/Vienna",
}
和一个碳间隔实例
$b = CarbonInterval::make('1month');
CarbonCarbonInterval {
"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,
}
如何在碳实例中添加间隔,以便我得到
CarbonCarbon {
"date": "2018-07-11 10:00:00",
"timezone_type": 3,
"timezone": "Europe/Vienna",
}
我知道涉及将其转换为时间戳或日期时间类的解决方案,
例如strtotime( date('Y-m-d H:i:s', strtotime("+1 month", $a->timestamp ) ) );
这就是我目前正在使用的,但我正在寻找一种更"碳化"的方式,我通过官方网站搜索了一下,但找不到任何内容,所以需要一些帮助。
更新: 只是为了给你背景 在前端我有两个控件 第一个是间隔(天,月,年(第二个是一个文本框,因此根据组合,我动态生成字符串,例如"2
days
","3
months
"等,然后获取间隔类的提要
我不知道有内置函数可以添加间隔,但是应该有效的是将间隔的总秒数添加到日期:
$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
基于DateTime
,而CarbonInterval
基于DateInterval
。有关方法参考,请参阅此处。
请参阅文档 https://carbon.nesbot.com/docs/#api-addsub
$carbon = CarbonCarbon::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 = CarbonCarbon::now();
dd($carbon->{$addInterval}($count));
dd($carbon->{$subInterval}($count));