Skip to content
Advertisement

Laravel Carbon change date to specific data

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 (CarbonCarbon::parse($date->start)->month < CarbonCarbon::parse($date->end)->month && CarbonCarbon::now()->month != CarbonCarbon::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?

Advertisement

Answer

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

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

But I would warn about mutating values from inside the template, it sounds 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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement