用JavaScript计算时间

时间:2018-12-11 19:36:14

标签: javascript

我正在使用此公式来计算2个不同字段之间的时间,但结果是整数,我需要小时/分钟

dateFromString之后的时间为例

var date1 = dateFromString(06: 00: 00);
var date2 = dateFromString(17: 30: 00);
var hours = Math.abs(date1 - date2) / 36e5;
return hours;

function dateFromString(isoDateString) {
  var parts = isoDateString.match(/\d+/g);
  var isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
  var isoDate = new Date(isoTime);
  return isoDate;
}

2 个答案:

答案 0 :(得分:0)

您的代码有一些语法错误,但是尝试一下,它应该以小时:分钟的格式给出时差:

var startTime = '06:00:00';
var endTime = '17:30:00';
var timeStart = new Date("01/01/2007 " + startTime);
var timeEnd = new Date("01/01/2007 " + endTime);

var minutesDiff = diff_minutes(timeStart, timeEnd);
var hoursAndMinsDiff = convertMinsToHrsMins(minutesDiff);

console.log(hoursAndMinsDiff)

function diff_minutes(dt2, dt1) {
    var diff = (dt2.getTime() - dt1.getTime()) / 1000;
    diff /= 60;
    return Math.abs(Math.round(diff));
}

function convertMinsToHrsMins(mins) {
    let h = Math.floor(mins / 60);
    let m = mins % 60;
    h = h < 10 ? '0' + h : h;
    m = m < 10 ? '0' + m : m;
    return `${h}:${m}`;
}

这是您要找的吗?

答案 1 :(得分:0)

使用除法获取小时,然后使用余数运算获得分钟。

此外,dateFromString()希望字符串具有日期和时间,而不仅仅是时间,并且它必须是带引号的字符串。

var date1 = dateFromString("2018-12-01 06:00:00");
var date2 = dateFromString("2018-11-30 17:30:00");
var diffmin = Math.floor(Math.abs(date1 - date2) / 60000);
var hours = Math.floor(diffmin/60);
var minutes = diffmin % 60;
console.log(hours, minutes);

function dateFromString(isoDateString) {
  var parts = isoDateString.match(/\d+/g);
  var isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
  var isoDate = new Date(isoTime);
  return isoDate;
}