I've been trying to figure out how to get the date of the last x day of a month in JavaScript without using a loop. I'm sure its to do with using the modulus operator but I cant quite get the formula right :-(
So for example the date for the last Monday in this month (06/2013) would be the 24th.
Can anyone shed some light on this? It's driving me nuts!
Thanks in advance.
Edit
I think I have it working now thanks to having a look inside how date.js
do it, I was close with what I had though!
function getLastDay(year, month, dayOfWeek)
{
var d = new Date(year, month, 0);
var diff = (dayOfWeek - d.getDay() + 7 * -1) % 7;
return new Date(year, month-1, d.getDate() + diff);
}
// Last Monday in for January 2013
getLastDay(2013, 1, 1); // Mon Jan 28 2013 00:00:00 GMT+0000 (GMT Standard Time)
Sorry, misread your question at first. Editing my response.
If you're willing to use a library, try date.js.
You can use the moveToNthOccurence with -1 to get the last occurence of a day in the month.
So:
Date.today().moveToNthOccurrence(1, -1)
should give you the last Monday of this month.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.