Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add 1 hour to date Carbon?

I have datetime "2016-11-24 11:59:56". How can I add one hour to this date and compare it with current datetime?

I tried:

$date = "2016-11-24 11:59:56";
$date->addHour();
like image 908
Goga Avatar asked Nov 24 '16 13:11

Goga


People also ask

How do you add minutes to carbon?

If you need to add minute or more minutes in date then you can use carbon in laravel. carbon provide addMinute() and addMinutes() method to add minutes on carbon date object.

How do you add a carbon day?

Carbon provides addDay() and addDays() method to add days on carbon date object. So, we will see laravel carbon add days or how to add days in date in laravel 8. Using the carbon add() and sub() function you can change on date and time.

How do you convert DateTime to date in carbon?

The $dateTime variable has the current date format, so create a new variable bind it with Carbon class and access the createFromFormat() method here; you can see two parameters. The first param is the date format, and the second is also the date-time format; you have to pass your choice of format in format() .


2 Answers

Try to parse() it first:

$date = Carbon::parse('2016-11-24 11:59:56')->addHour();

Better way is to add datetime column to a dates variable:

protected $dates = ['datetime_column'];

Then you can just do this:

$date = $model->datetime_column->addHour();
like image 148
Alexey Mezenin Avatar answered Oct 19 '22 19:10

Alexey Mezenin


You can try this:

$date = "2016-11-24 11:59:56";
$carbon_date = Carbon::parse($date);
$carbon_date->addHours(1);

You can now compare the date using lt() & gt() methods of Carbon. See Carbon Comparison Docs for exploring more methods like - eq(), ne(), gte(), lte(), etc.

$carbon_date->lt(Carbon::now()); // Less then current datetime (returns boolean)
$carbon_date->gt(Carbon::now()); // Greater than current datetime (returns boolean)

Hope this helps!

like image 19
Saumya Rastogi Avatar answered Oct 19 '22 19:10

Saumya Rastogi