'Add days to date in Laravel
I am beginner in Laravel. I use in my project Laravel 5.8.
I have this code:
$userPromotionDays = $user->premiumDate; // 2019.08.28
$daysToAdd = 5
How can I add $userPromotionDays to $daysToAdd (in Laravel/Carbon)?
Solution 1:[1]
You can create date with custom format and then add days to it using carbon.
$date = Carbon::createFromFormat('Y.m.d', $user->premiumDate);
$daysToAdd = 5;
$date = $date->addDays($daysToAdd);
dd($date);
You can see details documentation here.
Solution 2:[2]
Laravel uses the package called Carbon by nesbot.com, and this is how you add days:
$user->premiumDate->addDays(5);
https://carbon.nesbot.com/docs/#api-addsub
This will only work if you have casted the field premiumDate as a date field in the model.
https://laravel.com/docs/5.8/eloquent-mutators#date-mutators
Solution 3:[3]
You can add dates to your date like this, if your date is carbon instance:
$userPromotionDays->addDays($daysToAdd);
If your date isn't instance of Carbon, initiate it:
$userPromotionDays = Carbon::createFromFormat('Y.m.d', $user->premiumDate);
$userPromotionDays->addDays($daysToAdd);
Not tested, but should work.
Solution 4:[4]
use this code
date("Y-m-d", strtotime('+ '.daysToAdd , strtotime($userPromotionDays)));
check this link Adding days to specific day
Solution 5:[5]
You can use addDays() method of Carbon. First create a Carbon date object with createFromFormat and then add days.
Carbon::createFromFormat('Y.m.d', $user->premiumDate)->addDays($daysToAdd);
Solution 6:[6]
Without Carbon
For full example go to - https://www.php.net/manual/en/datetime.add.php
below code is for only add days
$d->add(new DateInterval('P10D'));
date_default_timezone_set("Asia/Kolkata");
$fineStamp = date('Y-m-d\TH:i:s').substr(microtime(), 1, 9);
$d = new DateTime($fineStamp);
$d->add(new DateInterval('P10D'));
$date=$d->format('Y-m-d H:i:s.u').PHP_EOL;
return substr($date, 0, -2);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rahul |
| Solution 2 | Latheesan |
| Solution 3 | zlatan |
| Solution 4 | |
| Solution 5 | Harun Yilmaz |
| Solution 6 | Mr. A |
