如何计算Javascript的总小时数?

时间:2018-06-12 10:28:41

标签: javascript math frontend

我需要使用JS计算时间跨度内的总小时数, 时间跨度的一个例子

10:00 - 16:00

所以答案是:6个小时,但我如何在JS中解决这个问题?

5 个答案:

答案 0 :(得分:1)

//Using MomentJs
var a = moment([10,00] , "HH:mm");
var b = moment([16,00] , "HH:mm");
console.log(b.diff(a, 'hours'))
<script src="https://momentjs.com/downloads/moment.min.js"></script>

答案 1 :(得分:0)

尝试以下

&#13;
&#13;
let dif = new Date("01/01/2018 " + "16:00").getHours() - 
new Date("01/01/2018 " + "10:00").getHours();

console.log(dif);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

&#13;
&#13;
//Using Js
var a = new Date("12 May, 2018 10:00");
var b = new Date("12 May, 2018 16:00");
var hours = Math.abs(b - a) / 36e5;
console.log(hours)
&#13;
&#13;
&#13;

答案 3 :(得分:0)

//new Date("YYYY-MM-DDTHH:mm:ssZ")

var date1 = new Date("2015-03-25T12:00:00Z");
var date2 = new Date("2015-03-24T19:00:00Z");
var hours = Math.abs(date1.getHours() - date2.getHours());
console.log(hours);

答案 4 :(得分:0)

var start = new Date();
var finish = new Date();
start = start.setHours(10);
finish = finish.setHours(16);
var totalHours = finish - start;
totalHours = totalHours/3600000; // milleseconds in one hour
console.log(totalHours);