Skip to content
Advertisement

Issue with getting the day of a month with the week day and year

I’m trying to get the day of a month with this code:

// your input
$month      = "September";
$year       = "2013";
$dayWeek    = "Friday";
$week       = 2;

// create a date object
$date = new DateTime();

// set to the first day of the specified year/month
$date->modify($year . '-' . $month . '-01');

// add $week -1 weeks to the date
$date->modify('+' . ($week - 1) . ' week');

// set to day of week
$date->modify($dayWeek);

// here's the day of month for you
echo $date->format('j');

BUT this code is not working, why not?

Because if I have this data:

$month      = "December";
$year       = "2019";
$dayWeek    = "saturday";
$week       = 2;

It should return 07 because if we look at the calendar in December 2019… the first week is just Sunday, BUT it returns 14 and I wonder why?? If 14 th of December is in the third week..

I’d like to know or to get a code which it gives me the day of a month… just giving $month, $year, dayWeek and week of the month.

Advertisement

Answer

Look here

When you specify dayname the date, quote:

Moves to the next day of this name.

Therefore,

$date->modify($year . '-' . $month . '-01');

gives you 2019, December 1st, which is Sunday

$date->modify('+' . ($week - 1) . ' week');

adds 1 week, the date now Dec 8th, Sunday

And

$date->modify($dayWeek);

looks for the next saturday, which is Dec 14th, which is exactly second saturday in the month.

This may solve your issue.

<?php
// your input
$month      = "December";
$year       = "2019";
$dayWeek    = "saturday";
$week       = 2;


// create a date object
$date = new DateTime();

$date->modify($year . '-' . $month . '-01');

$date->modify('sunday');  // Put here 'saturday' if your week ends with saturday and starts with sunday

$end_of_the_first_week = $date->format('j');

// Start over again
$date->modify($year . '-' . $month . '-01');

$date->modify($dayWeek);

if ($date->format('j') > $end_of_the_first_week) { // we already in the second week
  if ($week > 2) { 
    // add $week -2 weeks to the date
    $date->modify('+' . ($week - 2) . ' week');
  }
} else if ($week > 1) {
    // add $week -1 weeks to the date
    $date->modify('+' . ($week - 1) . ' week');
}

echo $date->format('j'); // 7 
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement