Set end of day instead of 00:00:00 in laravel
Asked Answered
L

4

6

When we pass a date value like this 2019-01-01 without the time 10:00:00, the time defaults to 00:00:00. So finally the db compatible value gets transformed into this: 2019-01-01 00:00:00. How can I force default it to 23:59:00 instead?

Example: I need to set an expiry_date attribute, but if I only take the date input 2019-01-08 from user, the user is going to assume that they will have the entire day as expiry date, when in reality it will expire at the very first second of 2019-01-08 because of the implicit default time 00:00:00.

How do I overcome this? How can I set a mutator for expiry_date that would turn this 2019-01-01 00:00:00 into this 2019-01-01 23:59:00?

Lexy answered 8/1, 2019 at 6:20 Comment(1)
It might be simpler to just compare the date portions e.g. something like DATE(expiry_date) > CURDATE()Bloomsbury
C
9

Just use the following:

$expiryDate = Carbon::createFromFormat('Y-m-d', $date)->endOfDay()->toDateTimeString();

This will take the date (update date format if needed), switch to the end of the day and convert the resulting object into a date time string.

Or, use it as an attribute setter:

/**
 * @param $value
 */
public function setExpiryDateAttribute($value)
{
    $this->attributes['expiry_date'] = Carbon::createFromFormat('Y-m-d', $value)
        ->endOfDay()
        ->toDateTimeString();
}
Coaming answered 8/1, 2019 at 7:35 Comment(0)
I
1

You may use something like the strtotime() function to add something to the current timestamp. $expiry_date = date("Y-m-d H:i:s", strtotime('+5 hours')).

If you need variables in the function, you must use double quotes then like strtotime("+{$hours} hours"), however better you use strtotime(sprintf("+%d hours", $hours)) then.

Ist answered 8/1, 2019 at 6:30 Comment(0)
A
1

I used an DateTime property method like below:

date_create($your_date)->modify('+1 day -1 microsecond'),

It works on Laravel because datetime is PHP native.

-> Source <-

Annunciata answered 4/8, 2022 at 20:29 Comment(0)
N
0

just hard code the time of day:

$expiry_date = $your_date->format("Y-m-d 23:59:00");

Natter answered 21/9, 2023 at 18:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.