Created
July 21, 2018 10:35
-
-
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
This file contains 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 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