Carbon dates find out if today is thursday or go back
Asked Answered
S

1

8

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');
}

?>
Still answered 2/7, 2015 at 16:16 Comment(1)
I haven't used Carbon, but would something like this work? $date = Carbon('this thursday'); if ($date <= new Carbon()) { $date = Carbon('last thursday'); }Legist
S
18

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');
?>
Symphysis answered 2/7, 2015 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.