Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DmitriyWebDev/af06becef72e827067bc07650e2f3bd5 to your computer and use it in GitHub Desktop.
Save DmitriyWebDev/af06becef72e827067bc07650e2f3bd5 to your computer and use it in GitHub Desktop.
Get the difference in date with the current date using the Moment.js library
const someDate = "2018-05-21";
const differenceWithCurrentDate = getDateDifferenceWithCurrentDate( someDate );
// if today "2018-07-21" ( for example )
// differenceWithCurrentDate = {
// type: 'months',
// count: 2
// }
function getDateDifferenceWithCurrentDate(date) {
let difference = {
type: false,
count: false
};
const now = moment(new Date());
date = moment(date);
const duration = moment.duration(now.diff(date));
const years = Math.floor( duration.asYears() );
const months = Math.floor( duration.asMonths() );
if( years ) {
difference = {
type: 'years',
count: years
}
return difference;
}
difference = {
type: 'months',
count: months
};
return difference;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment