Reputation: 109
I am trying to work out an issue where I need to map the "Week Number" based on a Meeting Day (ie Friday) using the Carbon Date plugin for Laravel
With the current month (March 2020), the 1st falls on a Sunday. However I don't want Carbon to treat this as Week 1, and the following week as week 2. I would like the app to look at the how many Fridays in a Month and take that as how many weeks in a month.
I am using this in my Controller
$date = Carbon::parse($request->get('rolldate'))->format('Y-m-d');
$e = new Rollmapping();
$e->roll_date = Carbon::parse($request->get('rolldate'));
$e->roll_year = Carbon::parse($date)->year;
$e->roll_month = Carbon::parse($date)->month;
$e->roll_week = Carbon::parse($date)->weekNumberInMonth;
$e->save();
However if I create a Roll on the 6th March I will get 2 for roll_week, were I would like 1 as this is the first Friday and continue from there, ie the following week (13th) would be week 2 and not week 3
Upvotes: 2
Views: 7760
Reputation: 4992
Probably you have to use weekOfMonth
property instead of weekNumberInMonth
weekOfMonthweekNumberInMonth consider weeks from monday to sunday, so the week 1 will contain 1 day if the month start with a sunday, and up to 7 if it starts with a monday.
weekOfMonth will returns 1 for the 7 first days of the month, then 2 from the 8th to the 14th, 3 from the 15th to the 21st, 4 from 22nd to 28th and 5 above
echo \Carbon\Carbon::parse('first friday')->weekOfMonth;
> 1
echo \Carbon\Carbon::parse('first friday')->weekNumberInMonth;
> 2
Also you have to consider if first day of month is between sunday to friday folowing comparasions:
var_dump(\Carbon\Carbon::parse('first day')->gt('first sunday') && \Carbon\Carbon::parse('first day')->lt('first friday'));
> false
If so you have to add 1 to weekOfMonth
property
Hope this helps you
Upvotes: 2