比较javascript上的datetime将它们转换为unixtime

时间:2017-09-27 14:33:28

标签: javascript

我有两个像这样的

形成的变量
2017-09-27 16:26:39

2017-09-28 06:30:00

3 个答案:

答案 0 :(得分:1)

您可以使用Date.parse将变量转换为unix时间戳。然后你可以比较两个时间戳,如下所示。

var unixtimeOne = Date.parse("2017-09-27 16:26:39");
var unixtimeTwo = Date.parse("2017-09-28 06:30:00");

console.log(unixtimeOne);
console.log(unixtimeTwo);
  
// You could compare the timestamps as follows
console.log(unixtimeOne < unixtimeTwo)

答案 1 :(得分:0)

    var date1 = new Date('2017 09-27 16:26:39');
    var date2 = new Date('2017-09-28 06:30:00');

    var msecs1 = date1.getTime(); // in milliseconds
    var msecs2 = date2.getTime(); // in milliseconds

    console.log(msecs1 - msecs2); // -50601000

答案 2 :(得分:0)

如果您愿意使用moment.js,它会为您提供很好的比较方法,例如'isSame','isAfter'和'isBefore':

var x = moment('2017-09-27 16:26:39');
var y = moment('2017-09-28 06:30:00');

x.isSame(y) //false
x.isAfter(y) //false
x.isBefore(y) //true

要查找两个日期时间之间的时差:

y.diff(x, 'hours') //14