Skip to content

Instantly share code, notes, and snippets.

@eduardoedson
Last active April 20, 2022 14:40
Show Gist options
  • Save eduardoedson/f9219fc1b058c2b78dcafb37cdca9333 to your computer and use it in GitHub Desktop.
Save eduardoedson/f9219fc1b058c2b78dcafb37cdca9333 to your computer and use it in GitHub Desktop.
Difference between two dates JS
function diffDate(dateInit, dateEnd) {
const d1 = new Date(dateInit).getTime()
const d2 = new Date(dateEnd).getTime()
if (d1 === d2) {
return {
'TotalDays' : 0,
'Result' : 'The two dates are the same.'
}
} else {
const diff = d1 > d2 ? new Date(d1 - d2) : new Date(d2 - d1)
const date = `${diff.getUTCFullYear()}-${diff.getMonth() + 1}-${diff.getDate()}`
const days = parseInt(Math.abs(date.split('-')[2]))
const months = parseInt(Math.abs(date.split('-')[1]) - 1)
const years = parseInt(Math.abs(date.split('-')[0] - 1970))
const dayTxt = ['day', 'days']
const monthTxt = ['month', 'months']
const yearTxt = ['year', 'years']
return {
'TotalDays' : Math.round((years * 365) + (months * 30.417) + days),
'Result' : `${years} ${years === 1 ? yearTxt[0] : yearTxt[1]} ${months} ${months === 1 ? monthTxt[0] : monthTxt[1]} and ${days} ${days === 1 ? dayTxt[0] : dayTxt[1]}`
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment