Home > Net >  Laravel Carbon change date to specific data
Laravel Carbon change date to specific data

Time:03-02

How to change f.e. only month and day in existing date variable(object ?)?

I've got date type fields in db:

$table->date('start');
$table->date('end');

And then I want in blade view change according to special conditions.

@if (Carbon\Carbon::parse($date->start)->month < Carbon\Carbon::parse($date->end)->month && Carbon\Carbon::now()->month != Carbon\Carbon::parse($date->start)->month)
@php
    $date->start = date('Y-m-d', '05');
@endphp
@endif

Above code changes the date to something like "1970-01-01". The year could stay as it is stored in current variable, but I need to know how change only month and day of current date.

For example if I check the current date month isn't equal to the variable, then I change the date to current month.

Is it possible?

CodePudding user response:

You can do it with setters and format (method inherited from DateTime):

$date->start = Carbon\Carbon::parse($date->start)->startOfMonth()->setMonth(5)->setDay(13)->format('Y-m-d');

But I would warn about mutating values from inside the template, it should like an anti-pattern. Prefer to create an other variable like $formattedDateStart to keep things cleans and your original data unmodified.

Or you can simply call the ->format() method only when you need it for display without actually storing this result anywhere.

EDIT: ->startOfMonth() added to avoid trouble if the current day is not available in the chosen month.

  • Related