Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carbon dates find out if today is thursday or go back

Tags:

php

php-carbon

I have the below code running in one of my scripts and it works well, but feels rather clunky and long. I feel like there might be a much shorter way of achieving the same result. I also mean without using a shorthand if statement.

I need to find out if today is thursday and if not use the previous thursday as the date. Any thoughts / ideas would be great.

<?php

if (new Carbon('this thursday') > new Carbon()) {
    $date = Carbon('this thursday');
} else {
    $date = Carbon('last thursday');
}

?>
like image 769
Somk Avatar asked Jul 02 '15 16:07

Somk


People also ask

How do you find the current date using carbon?

Carbon today php require __DIR__ . '/vendor/autoload. php'; use Carbon\Carbon; $now = Carbon::now(); echo "$now\n"; $today = Carbon::today(); echo "$today\n"; Carbon::now returns the current date and time and Carbon:today returns the current date.

How do you subtract carbon days?

You can subtract days on current date using carbon in laravel 6, laravel 7, laravel 8 and laravel 9 version. If you need to subtract day or more days in date then you can use carbon in laravel. carbon provide subDay() and subDays() method to add days on carbon date object.

How do you convert dateTime to date in carbon?

The $dateTime variable has the current date format, so create a new variable bind it with Carbon class and access the createFromFormat() method here; you can see two parameters. The first param is the date format, and the second is also the date-time format; you have to pass your choice of format in format() .


1 Answers

According to http://carbon.nesbot.com/docs/#api-modifiers :

The $date will hold the date to be shown.

<?php
$today = new Carbon();
if($today->dayOfWeek == Carbon::THURSDAY)
    $date = $today;
else
    $date = new Carbon('last thursday');
?>
like image 143
Manan Avatar answered Oct 12 '22 07:10

Manan