Moment.js gives wrong difference between 2 dates

I use moment.js in my React application 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 1511638810 (Sat, November 25, 2017 19:40:10 GMT)
  • this.state.saleEndTimeis 1516909110(Thu, 25 January 2018 19:38:30 GMT)

However, he concludes

an hour

This is obviously not correct, it should be 2 months. What have I done wrong?

Using moment v2.19.2 with node v7.9.0


Edit: The output should be humanize'ed, and the time difference between this.state.saleStartTimeand this.state.saleEndTimecan vary from minutes to several months ...

+4
source share
1 answer

I did not know that it was a stamp unix.
You should use the method unix:

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

Fragment launch:

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>
Run codeHide result
+6
source

Source: https://habr.com/ru/post/1689832/


All Articles