Question

I'm looking to find which week a date is in for a month where the week begins on a Friday. So for example, the calendar would look like this:

Week count   F   Sa  Su  M   Tu  W   Th
----------------------------------------
       0         1   2   3   4   5   6
       1     7   8   9   10  11  12  13
       2     14  15  16  17  18  19  20
       3     ...

The input will be the date in timestamp format ($currentDate) and I am looking for output in the form of $weekCount.

Thanks

Was it helpful?

Solution

Just need to count the number of previous fridays by going back 7 days at a time until you find you have covered them all.

The loop will always go beyond the first friday to cover the normal case of Friday not being the first day in the month. If Friday IS the first day in the month, then you need to reduce the increment to account for the overshoot.

    $currentDate = time(); // e.g.

    $dayOfMonth = date('j', $currentDate);

    $ym = date('Y-m', $currentDate);

    $firstFriday = strtotime("Friday ".$ym);

    $dateOfFirstFriday = date('j', $firstFriday);

    // we need to reduce count by 1 if friday is the 1st, to compensate
    // for overshooting by a week due to the >= in the while loop
    $weekCount = ($dateOfFirstFriday == 1) ? -1 : 0;

    while ($dayOfMonth >= $dateOfFirstFriday) {
        $weekCount ++;
        $dayOfMonth = $dayOfMonth - 7;
    }

    var_dump($weekCount);

This code doesn't account for if we are on say Fri 30th, then actually are we in week 0 of the next month? Not clear though from opening post if that is required.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top