Skip to content

Instantly share code, notes, and snippets.

@mnewt
Last active March 23, 2017 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnewt/1f7388ef1a9a8872d5d0b247d099bd73 to your computer and use it in GitHub Desktop.
Save mnewt/1f7388ef1a9a8872d5d0b247d099bd73 to your computer and use it in GitHub Desktop.
Print a simple HTML calendar using javascript with no dependencies (except pure.css)
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
Date.prototype.monthDays = function() {
var d = new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
Date.prototype.firstWeekdayOfMonth = function() {
var d = new Date(this.getFullYear(), this.getMonth(), 1);
return d.getDay();
}
Date.prototype.formatMonth = function () {
const monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
return monthNames[this.getMonth()];
}
function calendar (month) {
const calendarDayHTML = '<div class="pure-u-1-8 calendar-day">{0}</div>';
var html = `
<div class="pure-g calendar-table">
<div class="pure-u-1">
<h3>${month.getFullYear()} ${month.formatMonth()}</h3>
</div>`;
// Insert blank space for weekdays falling on previous month
for (i=month.firstWeekdayOfMonth(); i>0; --i) {
html += calendarDayHTML.format('&nbsp;');
}
// Print days
for (i=0; i<month.monthDays(); ++i) {
((month.firstWeekdayOfMonth() % 7) == 0) ? html += calendarDayHTML.format('&nbsp;'): '';
html += calendarDayHTML.format(i+1);
}
return html;
}
var root = document.getElementById('calendar');
root.innerHTML = calendar(new Date);
<div id="calendar"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment