2017-05-02 53 views
4

我需要比较两个不同的日期时间字符串(形成:YYYY-MM-DD'T'HH:mm)。JavaScript - 两个时间字符串之间的差异

下面是日期时间字符串:

var a = ("2017-05-02T10:45"); 
var b = ("2017-05-02T12:15"); 

我切的日期了出来,所以我只需要的时间(形成的:HH:MM)。

var now = a.slice(11, 16); 
var then = b.slice(11, 16); 

// now = 10:45 
// then = 12:15 

有没有什么办法可以得到这两个时间的区别?

结果应该是这样的:

1 hour 30 minutes 

此外,如果日期不同有没有简单的解决方案来获得日期区别吗?

+0

旁注/时间字符串,**不** **时间戳 – hindmost

+0

@最后谢谢,修正了标题 – IlariM

+0

我强烈建议您使用[Moment.js](https://momentjs.com/)来格式化日期/日期差异。 – hindmost

回答

0

这应该让你开始:

d1 = new Date(Date.parse("2017-05-02T10:45")); 
 
d2 = new Date(Date.parse("2017-05-02T12:15")); 
 

 
var getDuration = function(d1, d2) { 
 
    d3 = new Date(d2 - d1); 
 
    d0 = new Date(0); 
 

 
    return { 
 
     getHours: function(){ 
 
      return d3.getHours() - d0.getHours(); 
 
     }, 
 
     getMinutes: function(){ 
 
      return d3.getMinutes() - d0.getMinutes(); 
 
     }, 
 
     getMilliseconds: function() { 
 
      return d3.getMilliseconds() - d0.getMilliseconds(); 
 
     }, 
 
     toString: function(){ 
 
      return this.getHours() + ":" + 
 
        this.getMinutes() + ":" + 
 
        this.getMilliseconds(); 
 
     }, 
 
    }; 
 
} 
 

 
diff = getDuration(d1, d2); 
 

 
console.log(diff.toString());

或使用momentjs因为,1。这是很好的测试和错误跟踪。 2.从头开始编码是一种有趣的学习体验,但如果您处于公司环境中,从头开始编码会浪费时间(从而浪费金钱)。

+0

谢谢,这很好。 – IlariM

+0

不客气。从头开始编码是一种有趣的学习体验,但我真的建议你使用[newjs](http://momentjs.com/) – mika

+0

'new Date(Date.parse(“2017-05-02T10:45”))'是相同的到'新日期(“2017-05-02T10:45”)',只需输入更多内容。如果持续时间大于24小时,这也会失败。最好以毫秒为单位获得差值,然后手动转换为所需的时间格式。 – RobG

3

使用JavaScript日期:

var a = ("2017-05-02T10:45"); 
var b = ("2017-05-02T12:15"); 
var milliseconds = ((new Date(a)) - (new Date(b))); 

var minutes = milliseconds/(60000);