如何计算两个日期时间之间的差异?使用Javascript

时间:2018-01-20 18:58:18

标签: javascript datetime

有谁知道如何计算Javascript中两个日期时间之间的差异?

例如:2018-01-17T21:18:002018-01-16T21:17:00

我试图将它们拆分并在之后将它们加在一起,但我注意到时间已经在日期差异中计算出来了。

为什么人们不理解日期和日期时间之间的简单区别?停止投票,或撰写有关stuipid的评论。

2 个答案:

答案 0 :(得分:1)

如果您获得负值,请使用Math.abs(例如,如果您不知道a是否低于b

Date对象本质上是一个数字,您可以使用它进行数学运算而无需获取时间戳



var a = new Date('2018-01-17T21:18:00')
var b = new Date('2018-01-16T21:17:00')

console.log(a - b) // possible use
console.log(Math.abs(a - b)) // safe to use
console.log(Math.abs(b - a)) // safe to use
console.log(b - a) // not what you want




从那里你只计算有多少天/小时/分钟

答案 1 :(得分:0)

你可以使用valueOf - > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf



let date1 = new Date('2018-01-17T21:18:00')
let date2 = new Date('2018-01-16T21:17:00')
//you get the difference in ms
let difference = Math.abs(date1.valueOf()-date2.valueOf())
//you can then convert to any format




相关问题