-
-
Save HomerJSimpson/6093931 to your computer and use it in GitHub Desktop.
/*jslint plusplus:true, white:true */ | |
/*global console:false */ | |
function secondMonday(year, month) { "use strict"; | |
var firstDay = new Date(year, month, 1); | |
if(firstDay.getDay() !== 1) { | |
firstDay.setDate( | |
firstDay.getDay() === 0 ? 2 : 9 - firstDay.getDay() | |
); | |
} | |
firstDay.setDate(firstDay.getDate() + 7); | |
return firstDay; | |
} | |
var year, month; | |
for(year=2017;year>2013;--year) { | |
for(month=0;month<12;++month) { | |
console.log(secondMonday(year, 11-month) + "\n"); | |
} | |
} |
@heymartinadams looks amazing.
But it seems there is a bug, for example with the following parameters:
let year = 2022, month = 8, ordinal = 1, weekday = 'Wed'
thre result is 2022-08-31T00:00:00.000Z
but it should be 2022-09-07T00:00:00.000Z, not?
i think it should be
7 * ordinal + dayOfWeek - date.getUTCDay() - (date.getUTCDay() < dayOfWeek ? 7 : 0);
so only < not <= in the last part of the formula (date.getUTCDay() < dayOfWeek ? 7 : 0)
Hey @KevDev99 haven’t verified it (and don’t have the brainpower to do so at the moment — too busy with other stuff), but I’ll take your word for it! Thank you ✨
Had to do another calculation for last [weekday] of the month (e.g. last Sunday of August 2022) — as opposed to first, second, etc. Hat tip to @brucemcpherson for this snippet and to Dennis R. for this snippet:
let year = 2022, month = 7, ordinal = 'last', weekday = 'Sun'
let d
const dayOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].findIndex(x => x === weekday)
// Get the date of the last weekday: e.g. ordinal = 'last', weekday = 'Tue' of the month
if (ordinal === 'last') {
// Last day of desired month
d = new Date(year + (month.getMonth() === 11 ? 1 : 0), (month.getMonth() + 1) % 12, 0)
d.setUTCHours(0, 0, 0, 0)
// Find out what day of week that is and adjust
d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 7 - dayOfWeek) % 7)) // Note difference btw `getDate()` and `getDay()`
console.log(ordinal, weekday, d)
}
Hey, I created a script to get the date of any ordinal weekday (e.g. “first Sunday”, or “third Tuesday”). Posting here for anyone else interested.