Skip to content

Instantly share code, notes, and snippets.

@whyDontI
Last active September 25, 2020 15:45
Show Gist options
  • Save whyDontI/eeee32d5fb557dc876c19f9b173c477c to your computer and use it in GitHub Desktop.
Save whyDontI/eeee32d5fb557dc876c19f9b173c477c to your computer and use it in GitHub Desktop.
Count the difference between two dates
/**
* Returns true if year is a leap year
* @param {Number} year
*/
function isLeapYear(year) {
return (((year % 4 == 0) && (year % 100 !== 0)) || (year % 400 == 0))
}
/**
* Returns number of days till current month from start of the year
* @param {Number} month
* @param {Number} year
*/
function countDaysTillCurrentMonth(month, year) {
let days = 0
let monthDayCount = [
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
]
for (let i = 0; i < month - 1; i++) {
days += monthDayCount[i]
}
return days + ((month > 2) && isLeapYear(year) ? 1 : 0)
}
/**
* Returns number of leap years between two years
* @param {Number} from
* @param {Number} to
*/
function numberOfLeapYears(from, to) {
let i = from
let leapCount = 0
while (i < to) {
if (isLeapYear(i)) {
leapCount++
i += 4
} else {
i++
}
}
return leapCount
}
/**
* Returns difference of days between two years
* @param {Number} from
* @param {Number} to
*/
function daysBetweenYears(from, to) {
if (from === to)
return 0
return ((to - from) * 365) + numberOfLeapYears(from, to)
}
/**
* Returns the difference between two dates
* @param {String} from - date in following format 'YYYY-MM-DD'
* @param {String} to - date in following format 'YYYY-MM-DD'
*/
function countDateDifference(from, to) {
let startDate = {
year: parseInt(from.split('-')[0]),
month: parseInt(from.split('-')[1]),
day: parseInt(from.split('-')[2])
}
let endDate = {
year: parseInt(to.split('-')[0]),
month: parseInt(to.split('-')[1]),
day: parseInt(to.split('-')[2])
}
let numberOfDaysTillStartDate = countDaysTillCurrentMonth(startDate.month, startDate.year) + startDate.day
let numberOfDaysTillEndDate = countDaysTillCurrentMonth(endDate.month, endDate.year) + endDate.day + daysBetweenYears(startDate.year, endDate.year)
return Math.abs(numberOfDaysTillEndDate - numberOfDaysTillStartDate - 1)
}
// Test Cases
console.log('Test countDateDifference - start')
console.log(countDateDifference('2020-09-25', '2020-09-28') === 2) // true
console.log(countDateDifference('2020-09-25', '2020-09-29') === 3) // true
console.log(countDateDifference('2000-01-01', '2000-12-31') === 364) // true
console.log(countDateDifference('2000-12-30', '2001-01-02') === 2) // true
console.log(countDateDifference('1999`-12-30', '2001-01-02') === 368) // true
console.log('Test countDateDifference - End')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment