I have a carbon instance
$a = Carbon\Carbon::now();
Carbon\Carbon {
"date": "2018-06-11 10:00:00",
"timezone_type": 3,
"timezone": "Europe/Vienna",
}
and a CarbonInterval instance
$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,
}
How to add the interval in the carbon instance so that I would get
Carbon\Carbon {
"date": "2018-07-11 10:00:00",
"timezone_type": 3,
"timezone": "Europe/Vienna",
}
I am aware of solution that involve converting it to timestamp or Datetime class like this
strtotime( date('Y-m-d H:i:s', strtotime("+1 month", $a->timestamp ) ) );
which is what currently I am using but I am looking for a more "carbony" way I searched through the official site but couldn't find anything on this so need some help.
Update:
Just to give you the context
On frontend I have two controls 1st is for interval (days,months,year) 2nd is a text box so depending on the combination I generate strings dynamically like "2
days
" , "3
months
" so on that then gets feed to interval classes
I'm not aware of a built-in function to add an interval, but what should work is adding the total seconds of an interval to the date:
$date = Carbon::now(); // 2018-06-11 17:54:34
$interval = CarbonInterval::make('1hour');
$laterThisDay = $date->addSeconds($interval->totalSeconds); // 2018-06-11 18:54:34
Edit: Found an easier way!
$date = Carbon::now(); // 2018-06-11 17:54:34
$interval = CarbonInterval::make('1hour');
$laterThisDay = $date->add($interval); // 2018-06-11 18:54:34
This works because Carbon
is based on DateTime
and CarbonInterval
is based on DateInterval
. See here for method reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With