如何获得以秒或分钟或小时为单位的时差?

时间:2018-04-30 05:37:48

标签: javascript typescript

我只有2个字符串值,例如02:00 PM10:00 PM。如何计算这两者的差异。

我这里没有约会。我只有时间。

1 个答案:

答案 0 :(得分:3)

你可以试试这个。我希望它可以帮到你:

function diff(start, end) {
 start = start.split(":");
 end = end.split(":");
 var startDate = new Date(0, 0, 0, start[0], start[1], 0);
 var endDate = new Date(0, 0, 0, end[0], end[1], 0);
 var diff = endDate.getTime() - startDate.getTime();
 var hours = Math.floor(diff / 1000 / 60 / 60);
 diff -= hours * 1000 * 60 * 60;
 var minutes = Math.floor(diff / 1000 / 60);

// If using time pickers with 24 hours format, add the below line get exact hours
 if (hours < 0)
   hours = hours + 24;

 return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}