Hi Friends 👋,
Welcome To Infinitbility! ❤️
To subtract two dates in moment js, just use the moment()
and diff()
method to subtract dates and get the difference in milliseconds ( You can specify your measurement unit like seconds, minutes, hours, days months, or years ).
Just import a moment in your file and use moment()
to create a moment date after you can use the diff()
method like the following example.
1var a = moment([2007, 0, 29]);2var b = moment([2007, 0, 28]);3a.diff(b) // 86400000
Today, I’m going to show How do I subtract two dates in moment js, here I will use the momentjs common method moment()
to create the moment date object and the diff()
method to get the difference.
Let’s start the today’s tutorial How do you subtract two dates in moment js?
Table of content
- Installation
- Example in reactjs
Installation
Use the below installation command as per your package manager, moment support npm, Yarn, NuGet, spm, and meteor.
1npm install moment --save # npm2yarn add moment # Yarn3Install-Package Moment.js # NuGet4spm install moment --save # spm5meteor add momentjs:moment # meteor
Example in reactjs
In the following example, we are going to do
- import the moment package
- example of 24-hour format time
HH:mm:ss
- example of 12-hour format time
h:mm:ss a
let’s write the code.
1import moment from "moment";23function subtractDates() {4 var date1 = moment('2016-10-08 10:29:23');5 var date2 = moment('2021-10-08 11:06:55');67 // milliseconds8 date2.diff(date1); // 157768652000910 // seconds11 console.log(date2.diff(date1, 'seconds')) // 1577686521213 // minutes14 console.log(date2.diff(date1, 'minutes')) // 26294771516 // hours17 console.log(date2.diff(date1, 'hours')) // 438241819 // days20 console.log(date2.diff(date1, 'days')) // 18262122 // weeks23 console.log(date2.diff(date1, 'weeks')) // 2602425 // months26 console.log(date2.diff(date1, 'months')) // 602728 // years29 console.log(date2.diff(date1, 'years')) // 530}3132function App() {33 subtractDates()34 return (35 <div>36 {/* example of 24 hour format time `HH:mm:ss` */}37 {moment().format("HH:mm:ss")}38 </div>39 );40}4142export default App;
Note: By default, moment#diff will truncate the result to zero decimal places, returning an integer. If you want a floating point number, pass true as the third argument.
1var a = moment([2008, 9]);2var b = moment([2007, 0]);3a.diff(b, 'years'); // 14a.diff(b, 'years', true); // 1.75
In the above program, we call the moment()
and diff()
methods to subtract dates and get differences in years, months, weeks, days, hours, minutes, and seconds.
let’s check the output.

I hope it’s help you, All the best 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.