Last active
December 27, 2017 13:44
-
-
Save Woodsphreaker/e65b05618504f053fa6c324b02c154a5 to your computer and use it in GitHub Desktop.
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
const dateDiff = (d1, d2, type = "days") => { | |
const date1 = d1 instanceof Date ? d1 : new Date(`${d1.slice(6)}, ${d1.slice(3, 5)}, ${d1.slice(0, 2)}`) | |
const date2 = d2 instanceof Date ? d2 : new Date(`${d2.slice(6)}, ${d2.slice(3, 5)}, ${d2.slice(0, 2)}`) | |
return { | |
days: () => { | |
return Math.floor((date2.getTime() - date1.getTime()) / (24 * 3600 * 1000)) | |
}, | |
weeks: () => { | |
return Math.floor((date2.getTime() - date1.getTime()) / (24 * 3600 * 1000 * 7)) | |
}, | |
months: () => { | |
return Math.floor((date2.getMonth() + (date2.getFullYear() * 12)) - (date1.getMonth() + (date1.getFullYear() * 12))) | |
}, | |
years: () => { | |
return date2.getFullYear() - date1.getFullYear() | |
} | |
}[type]() | |
} | |
console.log(dateDiff("05/05/2011", new Date(), "years")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment