-6

input :17-07-2017
output->> 3rd Monday

Thanks in advance
Here is my code:

$datee = "2017-07-17";
$timestamp = strtotime($datee);
$day = date('l', $timestamp);
$week = date('w', $timestamp);
echo $day;
echo $week;
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
pallavi
  • 11
  • 1
  • 3
  • Use the `{}` toolbar button to nicely format the code. Clearly express what is the problem. What results you get and what you expect. – axiac Jul 11 '17 at 10:24
  • when i enter any date , i should get the number of week in month and day , example, if i typed 17-07-2017 i should get output as 3rd monday with above code i am getting wrong answer as Monday and 1 – pallavi Jul 11 '17 at 10:31

3 Answers3

2
$input = new \DateTime('2017-07-17');
$firstDayOfMonth = new \DateTime($input->format('Y-m-01'));
$order = (int)(($input->format('j') - 1) / 7) + 1;

function ordinal($number) {
    $ends = array('th','st','nd','rd','th','th','th','th','th','th');
    if ((($number % 100) >= 11) && (($number%100) <= 13))
        return $number. 'th';
    else
        return $number. $ends[$number % 10];
}

echo ordinal($order).' '.$input->format('l');

You can tinker with the code at https://3v4l.org/dg5Xa

Jirka Hrazdil
  • 3,983
  • 1
  • 14
  • 17
  • in some cases, it do not gives right answer eg. try date 2017-08-09 , its 2nd Wednesday but it gives 3rd... can you help me with this ? – pallavi Jul 14 '17 at 12:37
  • @pallavi: I have fixed the code. There was an excess `if` statement which produced wrong results. – Jirka Hrazdil Jul 17 '17 at 13:22
0

Very simple answer is already there

In PHP, how to know how many mondays have passed in this month uptil today?

$now=time();
if (($dow = date('w', $now)) == 0) $dow = 7; 
$begin = $now - (86400 * ($dow-1));

echo "Monday: ".ceil(date('d', $begin) / 7)."<br/>";
-1

'w' format is a numeric representation of the day (0 for Sunday, 6 for Saturday). It doesn't represent week of the month. To get the week of the month you can use the following function

 function week_number( $date = 'today' ) {   
        return ceil( date( 'j', strtotime( $date ) ) / 7 ); 
    } 

So your code should be:

  $datee = "2017-07-17";
  $timestamp = strtotime($datee);
  $day = date('l', $timestamp);
  $week = week_number($datee);
  echo $day;
  echo $week;

Reference: Get week number in month from date in PHP?

Sehdev
  • 5,486
  • 3
  • 11
  • 34
  • I believe the OP wanted not the week of month, but the occurence of day in the month. Your code returns 4 for Monday 2017-07-17, but it is only 3rd Monday of the month... – Jirka Hrazdil Jul 11 '17 at 10:39