How to find the last month of the month

I am not sure how to do this. I am creating a calendar in PHP and need it so that users can add a recurring event that follows the following rule:

Last [DOW] of the month (so last [Mon / W / Wed / etc] of the week)

I have a rule that is stored, I'm just not sure how best to extrapolate the last Mon / Tue / Wed of the month in PHP? I fell as if I were making it more complicated than it should be.

Assuming you have variables for $month=4, $dow=3and $year=2011how could I do this?

+5
source share
3 answers

, , , , strtotime - .

echo strtotime("last Monday of June 2011");

, date, , , , C, , , PHP ( , ).

, $month=4, $dow=3 $year=2011, $month , $dow .

+20

n- . , .

function get_Nth_dow($dow, $occurence, $m, $y)
{
    $numdays = date('t', mktime(0, 0, 0, $m, 1, $y));
    $add = 7 * ($occurence - 1);
    $firstdow = date('w', mktime(0, 0, 0, $m, 1, $y));
    $diff = $firstdow - $dow;

    $day_of_month = 1;
    if ($diff > 0)
    {
        $day_of_month += ($add - $diff);
    }
    elseif ($diff < $numdays)
    {
        $day_of_month -= ($diff - $add);
    }

    return $day_of_month;
}

$DOW= (0 = , 6 = ).

$X= (1 = , 2 = ..).

, . ,

7- ,

. $M= $Y=

: get_Nth_DOW(2,3,7,2009) 7- 2009 .

0

Here's an alternative:

<?
function lastDayOfMonth($month, $year) {
    switch ($month) {
        case 2:
            # if year is divisible by 4 and not divisible by 100
            if (($year % 4 == 0) && ($year % 100) > 0)
                return 29;
            # or if year is divisible by 400
            if ($year % 400 == 0)
                return 29;
            return 28;
        case 4:
        case 6:
        case 9:
        case 11:
            return 30; 
        default:
            return 31;
    }
}

function lastDayOfWeek($month, $year, $dow) {
    $d = new DateTime();

    #Finding the last day of month
    $d = $d->setDate($year, $month, lastDayOfMonth($month, $year));

    #Getting the day of week of last day of month
    $date_parts = getdate($d->getTimestamp());

    $diff = 0;

    #if we can't find the $dow in this week... (cause it would lie on next month)
    if ($dow > $date_parts['wday']) {
        # ...we go back a week.
        $diff -= 7;
    }

    return $date_parts['mday'] + $diff + ($dow - $date_parts['wday']);  
}

# checking the algorithm for this month...
for ($i=0; $i < 7; $i++) {
    echo lastDayOfWeek(6,2011,$i) . "<br>";
}

?>
0
source

All Articles