无法使用JavaScript计算时差

时间:2019-03-30 10:01:01

标签: javascript datetime

我需要使用JavaScript计算当前日期时间与用户输入日期时间之间的时差(以小时为单位)。这是我的代码:

var user_date = '31-03-2019';
        var dep_time='12:30PM';
        var datePieces = user_date.split("-");
        var mydate=[datePieces[1] , datePieces[0] , datePieces[2]].join("-");
        var todayDate = new Date();
        var todayMonth = todayDate.getMonth() + 1;
        var todayDay = todayDate.getDate();
        var todayYear = todayDate.getFullYear();
        if (todayDay < 10) {
          todayDay = '0' + todayDay;
        }
        if (todayMonth < 10) {
          todayMonth = '0' + todayMonth;
        }
        var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
        var inputToDate = Date.parse(mydate);
        var todayToDate = Date.parse(todayDateText);
        //console.log(inputToDate, todayToDate);
        //console.log(user_date, todayDateText);
        if (inputToDate > todayToDate) {
            var date=new Date;
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var ampm = hours >= 12 ? 'pm' : 'am';
            hours = hours % 12;
            hours = hours ? hours : 12; // the hour '0' should be '12'
            minutes = minutes < 10 ? '0'+minutes : minutes;
            var strTime = hours + ':' + minutes + ' ' + ampm;
            var timeStart = new Date(todayToDate + strTime);
            var timeEnd = new Date(mydate + dep_time);
            console.log(timeStart);
            console.log(timeEnd);
            var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
            var minutes = diff % 60;
            var hours = (diff - minutes) / 60;
            alert(hours);
        } else {

        }

我在这里得到输出NAN。我同时具有用户输入和当前日期时间,并且需要HRS中的时差。

1 个答案:

答案 0 :(得分:1)

1)Date.parse方法将日期转换为自1970年1月1日起的毫秒数。请参见https://www.w3schools.com/Jsref/jsref_parse.asp,因此将用户输入日期转换为自1970年1月1日起的毫秒数。

2)在Javascript中,新Date()对象上的getTime()方法获取自1970年1月1日到当前时间为止经过的毫秒数。

3)因此,找到这些毫秒之间的差将得到毫秒之间的差。

4)因为1小时= 3600000 ms,所以要找到小时差,请将答案除以3600000,得到小时差。

  • 您似乎也忘记了在解析日期时包含dep_time。

解决方法如下:

<script>
"use strict";
var user_date = '31-03-2019 12:30 PM';
        var datePieces = user_date.split("-");
        var mydate=[datePieces[1] , datePieces[0] , datePieces[2]].join("-");

        var todayDate = new Date();
        var todayToDate = todayDate.getTime();
        // In JavaScript, getTime() gets the number of milliseconds that have passed since January 1, 1970.

        var inputToDate = Date.parse(mydate);

        if (inputToDate > todayToDate) {
            var diff = (inputToDate - todayToDate) / 3600000; //Since 1 h = 3600000 ms
            alert(diff);
        } else {
            var diff = (todayToDate - inputToDate) / 3600000; //Since 1 h = 3600000 ms
            alert(diff);
        }
</script>