goslscs
goslscs

Reputation: 197

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)?

Upvotes: 7

Views: 53039

Answers (6)

Rahul
Rahul

Reputation: 18557

You can create date with custom format and then add days to it using carbon.

$date =2024-08-08;
$daysToAdd = 5;
$date = $date->addDays($daysToAdd);
dd($date);

You can see details documentation here.

Upvotes: 13

Apu Pradhan
Apu Pradhan

Reputation: 101

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);

Upvotes: 0

fatemeh sadeghi
fatemeh sadeghi

Reputation: 2583

use this code

date("Y-m-d", strtotime('+ '.daysToAdd , strtotime($userPromotionDays)));

check this link Adding days to specific day

Upvotes: 2

zlatan
zlatan

Reputation: 3951

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.

Upvotes: 5

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

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);

Upvotes: 0

Latheesan
Latheesan

Reputation: 24116

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

Upvotes: 6

Related Questions