Created
July 31, 2017 12:02
Using The Joyous Power Of Relative Dates To Calculate Days-In-Month In JavaScript
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
// I return the number of days in the given month. The year is required because the | |
// value may change in leap years. | |
function daysInMonth( month, year ) { | |
var lastDayOfMonth = new Date( | |
year, | |
// Go to the "next" month. This is always safe to do; if the next month is beyond | |
// the boundary of the current year, it will automatically become the appropriate | |
// month of the following year. For example, ( December + 1 ) ==> January. | |
( month + 1 ), | |
// Go to the "zero" day. Since days range from 1-31, the "0" day will | |
// automatically roll back to the last day of the previous month. And, since we | |
// did ( month + 1 ) above, it will be ( month + 1 - 1 ) ... or simply, the last | |
// day of "month". | |
0 | |
); | |
return( lastDayOfMonth.getDate() ); | |
} | |
// I return the name (abbreviation) of the given month index. | |
function monthAsString( month ) { | |
var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; | |
return( months[ month % 12 ] ); | |
} | |
// ----------------------------------------------------------------------------------- // | |
// ----------------------------------------------------------------------------------- // | |
// Let's test the months in 2016, since we know it's a leap year, and 2017, since we | |
// know it is not a leap year. And, since the Date object is a beast with relative | |
// dates, we can just loop over a 24-month period and the latter half of the loop will | |
// automatically roll over to the next year. | |
for ( var i = 0 ; i < 24 ; i++ ) { | |
console.log( `Days[ ${ monthAsString( i ) } ]: ${ daysInMonth( i, 2016 ) }` ); | |
// To make the console-logging easier to read, split 2016 and 2017. | |
( i === 11 ) && console.log( "----" ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment