0

Don,t think I can find this answer in this forum.

How to get the first week number in every month where month start by Monday. This month first week is 36 how to get that? Having this code. But don't work.

//get first week number in month

   $month = 9;
$year = 2018;
$day = 1;
$firstday = new DateTime("$year-$month-1");

$dow = (int)$firstday->format('w');

$firstday->add(new DateInterval('P' . ((8 - $dow) % 7) . 'D'));

$weeknumber = $firstday->format('W');

echo      $weeknumber    ;
2
  • this month first week is 36 how to get that?=>why 3 to 6 only why not 3 to 9?(including Friday, Saturday and Sunday) Commented Sep 6, 2018 at 13:17
  • 1
    Do you mean the W (uppercase) date format? php.net/manual/en/function.date.php Commented Sep 6, 2018 at 13:20

1 Answer 1

2

I think this code will do what you want. It first creates a DateTime object for the first of the month, then it moves that date forward to make it a Monday. Finally it prints the week of the year using format('W').

Edit

Updated code to print first Monday and week number for whole year

$year = 2018;
echo "Month | First Monday | Week\n";
for ($month = 1; $month <= 12; $month++) {
    $firstday = DateTime::createFromFormat('Y-n-j', "$year-$month-1");
    $dow = (int)$firstday->format('w');
    // update to a monday (day 1)
    $firstday->add(new DateInterval('P' . ((8 - $dow) % 7) . 'D'));
    echo sprintf("%5d |  %s  | %4d\n", $month, $firstday->format('Y-m-d'), $firstday->format('W'));
}

Output:

Month | First Monday | Week
    1 |  2018-01-01  |    1
    2 |  2018-02-05  |    6
    3 |  2018-03-05  |   10
    4 |  2018-04-02  |   14
    5 |  2018-05-07  |   19
    6 |  2018-06-04  |   23
    7 |  2018-07-02  |   27
    8 |  2018-08-06  |   32
    9 |  2018-09-03  |   36
   10 |  2018-10-01  |   40
   11 |  2018-11-05  |   45
   12 |  2018-12-03  |   49
Sign up to request clarification or add additional context in comments.

2 Comments

Updated my code getting 3636 as answer, ant not seems to work if I put month 8 or month 10 in. Month 10 is 5 weeks difference.
Hi @Jhonny I've edited the post to output first Mondays and week numbers for the whole year, it looks ok to me...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.