Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set end of day instead of 00:00:00 in laravel

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?

like image 741
Tanmay Avatar asked Jan 08 '19 06:01

Tanmay


1 Answers

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();
}
like image 165
Christian Kaal Avatar answered Sep 28 '22 00:09

Christian Kaal