Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find current day no. in month in php

Tags:

date

php

Today's date is 27-01-2014 so I got day name using following function:

$t=date('d-m-Y');
$day = strtolower(date("D",strtotime($t)));

So now the day name is mon.

How to find that this Monday is the forth Monday of current month? In other words, I am trying to find the 1st, 2nd, 3rd, 4th of a particular day (eg. Monday) of a month?

like image 719
DS9 Avatar asked Jan 27 '14 09:01

DS9


2 Answers

Credit for the Math part goes to Jon (above)

In combination with your code, full solution can be implemented as follows

$t=date('d-m-Y');
$dayName = strtolower(date("D",strtotime($t)));
$dayNum = strtolower(date("d",strtotime($t)));
echo floor(($dayNum - 1) / 7) + 1

or else as a function with optional date

PHP Fiddle here

This just return the number you are requesting.

function dayNumber($date=''){
    if($date==''){
        $t=date('d-m-Y');
    } else {
        $t=date('d-m-Y',strtotime($date));
    }

    $dayName = strtolower(date("D",strtotime($t)));
    $dayNum = strtolower(date("d",strtotime($t)));
    $return = floor(($dayNum - 1) / 7) + 1;
    return $return;
}


echo dayNumber('2014-01-27');
like image 115
Oliver M Grech Avatar answered Sep 28 '22 16:09

Oliver M Grech


$date = mktime(0, 0, 0, 1, 27, 2014);
$dayNumber = date("d", $date);
$dayOfWeek = date("l", $date);
$dayPosition = (floor(($dayNumber - 1) / 7) + 1);

switch ($dayPosition) {
    case 1:
        $suffix = 'st';
        break;
    case 2:
        $suffix = 'nd';
        break;
    case 3:
        $suffix = 'rd';
        break;
    default:
        $suffix = 'th';
}

echo "Today is the " . $dayPosition . $suffix . " " . $dayOfWeek . " of the month.";
// Will echo: Today is the 4th Monday of the month.

Thanks to @Jon for the maths.

like image 32
MrUpsidown Avatar answered Sep 28 '22 15:09

MrUpsidown