DEV Community

Cover image for Find No of days between 2 dates using moment.js
Atul Bhatt
Atul Bhatt

Posted on • Updated on

Find No of days between 2 dates using moment.js

Time and time again I'm reminded that you can't escape time and so are the problems related to date and time. One such very common problem is to find the difference between 2 dates.

Let me give you a very simple example where we will try to find the how many days old are you?
So it feels like not a such big deal but think of writing the entire logic on your own when you know you can write but it will much less of a hassle to do it via library like moment.

I'm writing this as an article here because it took me time to find the way to do it using moment itself. I'm writing this article more for myself than for others. So consider this as a treat.


Here's the code:

  let myDob = moment("19/12/1997", "DD/MM/YYYY");
  let today = moment();
  let myAge = today.diff(myDob, "years");
  let noOfDays = today.diff(myDob, "days");
Enter fullscreen mode Exit fullscreen mode

Below is the embedded sandbox to demonstrate it:

Check out the same in moment docs:
moment

Thanks for your time reading this. I hope it helped you. Have a productive day :)

PS:Moment is in maintenance mode.

You can read about the meaning of it in the article linked below.
MOMENT.JS OFFICIALLY BECOMES A LEGACY PROJECT IN MAINTENANCE MODE

Latest comments (2)

Collapse
 
lweiner profile image
Lukas Weiner

It would be nice if you would add a sentence that moment is now only in maintenance mode and that you should probably use another library if you start a new project.

Collapse
 
atulbhattsystem32 profile image
Atul Bhatt

Thank You for bringing this into my Notice. I will be honest that I myself wasn't aware of the fact while writing this article. I'll write a similar article to do it via date-fns. And I'll also add the fact that moment is in maintenance mode.