简体   繁体   中英

Moment.js giving Incorrect Difference between 2 Dates

I am using moment.js in my React app with the following code to find the difference between 2 unix timestamps :

import Moment from 'moment';

Moment.duration( 
    Moment(this.state.saleEndTime).diff(Moment(this.state.saleStartTime))
).humanize()

where

  • this.state.saleStartTime is 1511638810 (Sat, 25 Nov 2017 19:40:10 GMT)
  • this.state.saleEndTime is 1516909110 (Thu, 25 Jan 2018 19:38:30 GMT)

However it is giving the output

an hour

This is obviously not correct, it should be 2 months. What did I do wrongly?

Using moment v2.19.2 with node v7.9.0


Edit: Output needs to be humanize 'ed, and the time difference between this.state.saleStartTime and this.state.saleEndTime can range from minutes to months...

I didn't realize it's a unix stamp.
You should use the unix method then:

moment.duration(
  moment.unix(1516909110).diff(moment.unix(1511638810))
).humanize();

Running snippet:

 const result = moment.duration( moment.unix(1516909110).diff(moment.unix(1511638810)) ).humanize(); const App = () => ( <div > <div>{result}</div> </div> ); ReactDOM.render(<App />, document.getElementById('root')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/moment@2.19.2/moment.js"></script> <div id="root"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM