3

I am trying to count how many weekends (Saturday and Sunday) that falls in a given month. This will allow me to subtract these weekends to get number of actual weekdays required in my application.

What I am doing now is, firstly I created Carbon object like this:

$thisDate = Carbon::createFromDate(2014, 12, 2);

And then, I calculated the number of days in a month that falls in above date with the help of Carbon object like this

$daysInMonth = $thisDate->daysInMonth;

Now, I have got the number of days in a month. It is possible to find the number of weekends by looping each day of that month and checking whether it is weekend or not (something like CarbonObject->isWeekday) and increasing the counter but it seems quite messy.

Is there more elegant way to do this? I mean is there something better in CarbonObject that I am missing, which could give the result in much easier way?

Note: I am creating my application with the help of Laravel4.2

I have also read this: (But was wondering if there is Carbon-way solution) Get number of weekdays in a given month

Community
  • 1
  • 1
Nirmalz Thapaz
  • 925
  • 4
  • 13
  • 28

2 Answers2

5

You can use the diffInDaysFiltered() method to filter the number of days using the isWeekend() method, which will return the result you're after.

$dt = Carbon::create(2014, 1, 1);
$dt2 = Carbon::create(2014, 12, 31);
$daysForExtraCoding = $dt->diffInDaysFiltered(function(Carbon $date) {
    return $date->isWeekend();
}, $dt2);

echo $daysForExtraCoding;
Dwight
  • 12,120
  • 6
  • 51
  • 64
Maximilian Prepl
  • 402
  • 4
  • 10
  • Hello and welcome to Stack Overflow. Code only answers are usually not very useful unless they explain what they do. This is very true of long segments of code. Please consider adding an explanation of what you changed or wrote. – JasonMArcher Jan 06 '15 at 00:05
  • i don't think here is need for explication, because, this are 3 lines of code. 1,2 lines are creating date objects, third line filter dates. – Maximilian Prepl Jan 06 '15 at 00:29
  • Hi Max, thanks for the answer. i agree with @JasonMArcher it is always worth putting in explanation with your code. It is best to assume that whoever is reading your answer is unfamiliar with the subject area and a couple of comments go a long way to clearing things up. – Oli Folkerd Jan 07 '15 at 16:54
0

I have other solution for this

$dt = Carbon::create(2014, 12, 31); // day end of month
$numberOfWeeks = $dt->weekOfMonth;