Last active
September 28, 2022 22:14
-
-
Save HomerJSimpson/6093931 to your computer and use it in GitHub Desktop.
Calculate Second Monday of the month in javascript (not quite done)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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"); | |
} | |
} |
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)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ✨