如何检查时间是否大于javascript中2个日期之间的总时间

How to check if time is greater than the total time between 2 dates in javascript?

本文关键字:时间 2个 日期 之间 javascript 是否 何检查 检查 大于      更新时间:2023-09-26

我想检查时间12.55(这是那里的格式,我无法编辑格式)是否大于两个日期之间的总时间,例如"2015-10-12 10:00"和2015-10-12 12:00。我已经完成了求差值的第一部分,但是不知道求时间大于时差的第二部分。希望有人能帮助我!

var getDayTimeDiff = function(start, end){
    var date1 = new Date(start);
    var date2 = new Date(end);
    var diff = date2.getTime() - date1.getTime();
    var msec = diff;
    var hh = Math.floor(msec / 1000 / 60 / 60);
    msec -= hh * 1000 * 60 * 60;
    var mm = Math.floor(msec / 1000 / 60);
    msec -= mm * 1000 * 60;
    var ss = Math.floor(msec / 1000);
    msec -= ss * 1000;
    return diff;
}

var timeDiff = getDayTimeDiff("2015-10-12 10:00","2015-10-12 12:00");
console.log(timeDiff); // 7200000

var time2Calc = "12.55";

你可以把时间转换成毫秒,然后比较毫秒的差异,就像

var getDayTimeDiff = function(start, end) {
  var date1 = new Date(start);
  var date2 = new Date(end);
  return date2.getTime() - date1.getTime();
}
var toMillis = function(time) {
  var parts = time.split('.');
  return (parts[0] * 60 + +parts[1]) * 60 * 1000;
}
function test(t1, t2) {
  var timeDiff = getDayTimeDiff(t1, t2);
  var time2Calc = "12.55";
  var base = toMillis(time2Calc);
  var result = (Math.abs(timeDiff) > base);
  snippet.log(t1 + ' : ' + t2 + ' -> ' + result);
}
test("2015-10-12 10:00", "2015-10-12 23:00");
test("2015-10-12 10:00", "2015-10-12 12:00");
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

如果" time 12.55 "指的是12小时55分钟,只需将其转换为毫秒,并与timemediff进行比较。

E:

    function toMilli(time) {
        var a = time.split(".");
        return (a[0]*60 + a[1])*60*1000;
    }

在JavaScript中,使用Moment.js很容易进行日期和时间操作像

var duration = moment.duration(end.diff(startTime));
var hours = duration.asMilliseconds();