Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find the last monday of the month

Tags:

php

I'm not sure how to go about this one. I'm building a calendar in PHP and need users to be able to add a repeating event that follows the following rule:

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

I've got the rule itself stored, I'm just not sure how best to extrapolate the last Mon/Tue/Wed of the month in PHP? I fell like i'm making this more complicated than it needs to be.

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

like image 248
TH1981 Avatar asked Jun 25 '11 15:06

TH1981


1 Answers

For everything date-related that you can express in proper English but have a hard time expressing using numbers, strtotime is your best friend.

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

This returns a timestamp that you can use as the second parameter to date and the likes to get a proper, human-readable date. Since it's a built-in function written in C, this solution is also much faster than almost anything else you could come up with written in PHP (though I'm quite sure it wouldn't matter much in a real-world scenario).

So assuming you have $month=4, $dow=3 and $year=2011, you'll need an array mapping $month values to their English textual representations and another array mapping $dow values to their textual representations.

like image 72
zneak Avatar answered Oct 04 '22 19:10

zneak