4

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...

Nyxynyx
  • 61,411
  • 155
  • 482
  • 830
  • shouldn't you pass a unit to [diff](https://momentjs.com/docs/#/displaying/difference/)? – Sagiv b.g Nov 25 '17 at 20:01
  • Possible duplicate of [Get hours difference between two dates in Moment Js](https://stackoverflow.com/questions/25150570/get-hours-difference-between-two-dates-in-moment-js) – Matthew Spence Nov 25 '17 at 20:03
  • @Sag1v What unit should I pass if the 2 unix timestamps can be minutes or months apart, and the output should be `humanize`'ed? – Nyxynyx Nov 25 '17 at 20:06
  • 2
    @TheMintyMate Sorry for the confusion, it is not a duplicate. Edited question, Sag1v provided solution. Thanks – Nyxynyx Nov 25 '17 at 20:13

1 Answers1

6

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>
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99