Skip to content

Instantly share code, notes, and snippets.

@nuragic
Last active February 8, 2017 00:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nuragic/ff9ee6212a6d335627e1fd17a81e8991 to your computer and use it in GitHub Desktop.
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").
// 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