Last active
February 8, 2017 00:06
-
-
Save nuragic/ff9ee6212a6d335627e1fd17a81e8991 to your computer and use it in GitHub Desktop.
Get the difference between dates in a human readable format (like "2 years, 3 months").
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
// Both params accept the same format as the Date object (IETF-compliant RFC 2822 timestamps and also a version of ISO8601). | |
// This is a basic version (supports just years and months, it assumes every month is 30 days, no pluralization, etc.) but it works. | |
const getDuration = (startDateString, endDateString = new Date()) => { | |
const totalMonths = Math.floor((new Date(endDateString) - new Date(startDateString)) / 1000 / 60 / 60 / 24 / 30); | |
const months = totalMonths < 12 ? totalMonths : totalMonths % 12; | |
const years = Math.floor(totalMonths / 12); | |
let duration = '¯\_(ツ)_/¯'; | |
if (years === 0) | |
if (months > 0) | |
duration = `${months} months`; | |
if (years > 0) | |
if (months === 0) | |
duration = `${years} years`; | |
else | |
duration = `${years} years, ${months} months`; | |
return `${duration}`; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment