How to display the number of years and month since a date using moment.js

StackOverflow https://stackoverflow.com/questions/22269833

  •  11-06-2023
  •  | 
  •  

Question

I want to display something like this :

member for 1 year, 8 month

The example on the momment.js web site is :

moment("20120620", "YYYYMMDD").fromNow(); // 2 years ago.

How to display also the number of month since the provided date ?

Like : 2 years, 6 months

Thank you

Était-ce utile?

La solution

Ok I found the answer so I post it in case it can be useful for others:

var date = new Date(2011,5,24)   
var month = date.getMonth()
var year = date.getFullYear();

var dateString = moment(year, "YYYY").fromNow(true) + 
                 moment(month, "MM").fromNow(true)) +  " ago" 

console.log(dateString)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top