Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fabricecw's avatar

Carbon - get last weekday from date

Hey

How can I get the last weekday from a date with Carbon? I don't mean the last day of the week, but for example the last Thursday from 11.03 (Saturday) would be 09.03. And for 07.03 (Thuesday) it would be 02.03

Any ideas?

Thanks and regards,

0 likes
10 replies
J_shelfwood's avatar

You could create an array with all the weekdays in it so you can use the Key value pairs to count up/down depending on what day it is. So say it is indeed Saturday, that would be an index of 5, thursday would be 3 Which means you can subtract 2 days to get the last thursday.

Cronix's avatar

why not just use php's vanilla strtotime and ask for "last Thursday" or whatever you need?

fabricecw's avatar

Isn't this looking for the last Thursday from the current date? Is it possible to depend it from a specific date?

Of cause, this would make it much easier.

Regards,

Cronix's avatar

you can pass the date to use as base

Cronix's avatar
Cronix
Best Answer
Level 67

Something like:

$searchDay = 'Thursday';
$searchDate = new Carbon(); //or whatever Carbon instance you're using
$lastThursday = Carbon::createFromTimeStamp(strtotime("last $searchDay", $searchDate->timestamp));
1 like
tykus's avatar
$day = Thursday;

Carbon\Carbon::parse("last {$day}");
1 like
fabricecw's avatar

Thanks @Cronix !

@tykus : With this code, I can't pass a base date (reference last {day} from now, not a specific day).

Regards,

kirya-dev's avatar

today()->previous('Friday') or $model->created_at->copy()->previous('Friday')

cashcalc's avatar

You could even use the helper function now()->parse('Monday'); and to get the previous day just use now()->previous('Monday'); If today is Tuesday, it would return the date of yesterday (Monday)

Please or to participate in this conversation.