How to add 1 hour to date Carbon?
Asked Answered
B

3

24

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();
Burkley answered 24/11, 2016 at 13:30 Comment(0)
M
47

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();
Maryrosemarys answered 24/11, 2016 at 13:31 Comment(0)
A
22

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!

Anaclitic answered 24/11, 2016 at 13:41 Comment(0)
S
1

The new way is with $cast

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'locked_date' => 'datetime',
        'last_login' => 'datetime',
    ];

if($user->locked_date->addHour()->isPast()){}
Selfhood answered 17/4 at 13:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.