简体   繁体   English

Moment.js在2个日期之间给出不正确的差异

[英]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 : 我在我的React应用程序中使用了以下代码中的moment.js来查找2个unix时间戳之间的差异:

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.saleStartTime1511638810 (星期六,2017年11月25日19:40:10 GMT)
  • this.state.saleEndTime is 1516909110 (Thu, 25 Jan 2018 19:38:30 GMT) this.state.saleEndTime1516909110 (星期四,2018年1月25日19:38:30 GMT)

However it is giving the output 然而它正在给出输出

an hour

This is obviously not correct, it should be 2 months. 这显然不正确,应该是2个月。 What did I do wrongly? 我做错了什么?

Using moment v2.19.2 with node v7.9.0 将时刻v2.19.2与节点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... 编辑:输出需要humanizethis.state.saleStartTimethis.state.saleEndTime之间的this.state.saleEndTime可以从几分钟到几个月......

I didn't realize it's a unix stamp. 我没有意识到这是一张unix邮票。
You should use the unix method then: 您应该使用unix方法:

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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