Created
August 9, 2020 00:42
-
-
Save ChukwuEmekaAjah/6bac262939d2c609da48aa2d33a13100 to your computer and use it in GitHub Desktop.
A utility function that prints out an ordered calendar based on the passed in date or present day date. It was inspired by the Facebook page publishing tools date picker functionality.
This file contains hidden or 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
function isLeapYear(year){ | |
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); | |
} | |
function calendar(inputDate){ | |
const presentDate = inputDate ? (new Date(inputDate)) : (new Date()); | |
console.log("date is ", presentDate) | |
if(Boolean(presentDate) === false){ | |
console.log("invalid date provided."); | |
return; | |
} | |
const months = { | |
'0':31, | |
'1':isLeapYear(presentDate.getFullYear()) ? 29 : 28, | |
'2':31, | |
'3':30, | |
'4':31, | |
'5':30, | |
'6':31, | |
'7':31, | |
'8':30, | |
'9':31, | |
'10':30, | |
'11':31, | |
} | |
const monthNames = ['JAN','FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] | |
const month = presentDate.getMonth(); | |
console.log("Month is ", monthNames[month]) | |
const daysOfTheWeek = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']; | |
const firstDayOfMonth = (new Date(`${presentDate.getFullYear()}-${month+1}-01`)).getDay(); | |
const daysInMonth = months[month.toString()]; | |
const numberOfDaysInOneWeek = 7; | |
const numberOfWeeksInMonth = Math.ceil((daysInMonth+firstDayOfMonth)/numberOfDaysInOneWeek); | |
const calendarRows = []; | |
let calendarRow = (new Array(7).fill(' ')); | |
for(let u = 0; u < daysInMonth; u++){ | |
let dayPosition = (firstDayOfMonth + u) % numberOfDaysInOneWeek; | |
// check if we have gone to a new row and it's not empty | |
if(dayPosition == 0 && Boolean(calendarRow[calendarRow.length -1].trim()) == true){ | |
calendarRows.push(calendarRow); | |
calendarRow = (new Array(7)).fill(' '); | |
} | |
calendarRow[dayPosition] = u+1 < 10 ? ` ${u+1}` : ` ${u+1}` | |
} | |
// add the last calendar row | |
if((numberOfWeeksInMonth - calendarRows.length) == 1){ | |
calendarRows.push(calendarRow); | |
} | |
console.log(daysOfTheWeek.join(' ')); | |
calendarRows.forEach((row) => { | |
console.log(row.join(' ')) | |
}) | |
} | |
calendar('2021-12'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment