Skip to content

Instantly share code, notes, and snippets.

@kkroesch
Created October 1, 2015 09:45
Show Gist options
  • Save kkroesch/915b910b523fa66d4116 to your computer and use it in GitHub Desktop.
Save kkroesch/915b910b523fa66d4116 to your computer and use it in GitHub Desktop.
Calendar-related calculations.
/*
* Calendar calculations
*
* The following enhancements on the standard JavaScript Date object
* allow advanced calculations for calendars, especially the
* calculation of the calendar weeks.
*
* @author Karsten Kroesch
*/
Date.prototype.isLeapYear = function() {
if (this.getFullYear() % 400 == 0) return true
if (this.getFullYear() % 100 == 0) return false
if (this.getFullYear() % 4 == 0) return true
return false
}
Date.prototype.getDaysPerMonth = function(month) {
var days_per_month = new Array(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
if (month == 2) {
if (this.isLeapYear(this.getYear()))
return 29
else
return 28
}
return days_per_month[month]
}
Date.prototype.getDayOfYear = function() {
var localMonth = this.getMonth()
var localDay = this.getDay()
while (localMonth > 1) {
localMonth --
localDay += this.getDaysPerMonth(localMonth)
}
return localDay
}
Date.prototype.getCalendarWeek = function() {
var jan1 = new Date(this.getYear(), 1, 1)
var dayJan1 = jan1.getDay()
var dayOfYear = this.getDayOfYear()
// Exception: Friday and Saturday
if (dayJan1 >= 4) dayJan1 -= 7
// Exception: Calendar week from year before
if ((dayOfYear + dayJan1) <= 0)
return new Date(this.getYear() - 1, 12, 31).getCalendarWeek()
var calendarWeek = ((dayOfYear - 1 + dayJan1) / 7) + 1
// Years starting on Thursday have 53 weeks except in leap years,
// where this is also possible for years starting on Wednesday
if (calendarWeek == 53) {
if ((dayJan1 == 3) || ((dayJan1 == 2) && this.isLeapYear())) {
;
} else {
calendarWeek = 1
}
}
return Math.round(calendarWeek)
}
Date.prototype.prevMonth = function() {
this.setMonth(this.getMonth() - 1)
return this
}
Date.prototype.nextMonth = function() {
this.setMonth(this.getMonth() + 1)
return this
}
/**
* Calculate difference in days between this and another date,
* which should be in the future to avoid negative days.
*/
Date.prototype.daysTo = function(date) {
return Math.round((date.getTime() - this.getTime()) / (1000 * 60 * 60 * 24))
}
Date.prototype.format = function() {
// NOTE: Month is zero-based, Jan = 0
return this.getDate() + '.' + (this.getMonth()+1) + '.' + this.getFullYear()
}
Date.prototype.time = function() {
var padH = this.getHours() > 9 ? '' : '0'
var padM = this.getMinutes() > 9 ? '' : '0'
return padH + this.getHours() + ':' + padM + this.getMinutes()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment