When I set date by week number of the year like this:
$date = Carbon::now(); $date->setISODate(2020,1);
I then get $date->month
as 12 when expect to get 1.
Is it correct behavior? Why in the case weekOfYear 1 the month is 12? And can I set that date by week number and get month 1?
Advertisement
Answer
You are getting confused with the concepts of calendar weeks. Officially the first week of the year is the one containing the first Thursday in that year. This means that week #1 in 2020 is between 2019-12-30 and 2020-01-05.
If you want to get the number of the month of the first week you must not look at the first day of the week but you must look at the Thursday of that week.
$date = Carbon::now(); $date->setISODate(2020, 1, 4); // 4 is Thursday echo $date->month; // month will be 1 for every year.
This will give you the Thursday in the first week of the year 2020 which falls already in 2020-01 and therefore month is 1.