JavaScript:显示迄今为止的差异,作为剩余时间。 (当天及以前怎么样)

时间:2016-10-04 11:48:50

标签: javascript date datetime

我想显示今天和所选日期时间之间的差异,以显示剩余时间。

我使用了堆栈溢出中提到的解决方案。但是我今天有问题! 当选定的日期是今天或之前,我的意思是,当差异(diffDays)不是正数时,我得到错误的结果。我该怎么办呢?

 $("#ServiceTime").change(
    function (e) {
        var firstDate = $(this).val();
        var secondDate = new Date();
        var diffDays = firstDate.getTime() - secondDate.getTime();
        var date = new Date(diffDays);
        var str = '';
        str += date.getUTCDate()-1 + " days and ";
        str += date.getUTCHours() + " hours and  ";
        str += date.getUTCMinutes() + " minutes";
        str += "remained...";
        $("#remainedHourToService").html(str);
        });

更新: 我不能单独使用abs,如果用户选择过去两天,他将会再次看到1天58分钟...'但是我想要0天0分钟......仍然是#39;

1 个答案:

答案 0 :(得分:0)

只需使用Math.abs()获取绝对值。

   $("#ServiceTime").change(function (e) {
        var firstDate = $(this).val();
        var second
        Date = new Date();
        var diffDays = Math.abs(firstDate.getTime() - secondDate.getTime());
        var date = new Date(diffDays);
        var str = '';
        str += date.getUTCDate()-1 + " days and ";
        str += date.getUTCHours() + " hours and  ";
        str += date.getUTCMinutes() + " minutes";
        str += "has remained...";
        $("#remainedHourToService").html(str);
    });

更新:

轻松解决该问题。 :)

  $("#ServiceTime").change(function (e) {
            var firstDate = $(this).val();
            var second
            Date = new Date();
            var diff = firstDate.getTime()-secondDate.getTime();
            var str2 = "";
            if(diff > 0) 
                str2 = "have remained...";
            else
                str2 = "have passed...";
            var diffDays = Math.abs(diff);
            var date = new Date(diffDays);
            var str = '';
            str += date.getUTCDate()-1 + " days and ";
            str += date.getUTCHours() + " hours and  ";
            str += date.getUTCMinutes() + " minutes";
            str += str2;
            $("#remainedHourToService").html(str);
        });