6

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

goslscs
  • 187
  • 1
  • 2
  • 10
  • Possible duplicate of [Incrementing dates with Carbon](https://stackoverflow.com/questions/35048657/incrementing-dates-with-carbon) – Arnaud Claudel Aug 28 '19 at 15:29

6 Answers6

11

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.

Rahul
  • 18,271
  • 7
  • 41
  • 60
5

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

Latheesan
  • 23,247
  • 32
  • 107
  • 201
5

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.

zlatan
  • 3,346
  • 2
  • 17
  • 35
2

use this code

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

check this link Adding days to specific day

fatemeh sadeghi
  • 1,757
  • 1
  • 11
  • 14
  • Please add some explanation to your code - as far as I see, it does not make use of `$daysToAdd`, and it does not use any Carbon features – Nico Haase Aug 28 '19 at 14:15
0

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);
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
0

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);
Mr. A
  • 71
  • 7