JavaScriptは2つの日付の時間差を計算します.

3349 ワード

 /**
     * 
     * @param startTime
     * @param endTime
     * @param diffType
     * @returns {Number|number}
     * @constructor
     */
    function GetDateDiff(startTime, endTime, diffType) {
        // xxxx-xx-xx     ,    xxxx/xx/xx   
        startTime = startTime.replace(/\-/g, "/");
        endTime = endTime.replace(/\-/g, "/");
        //              
        diffType = diffType.toLowerCase();
        var sTime = new Date(startTime);      //    
        var eTime = new Date(endTime);  //    
        //       
        var divNum = 1;
        switch (diffType) {
            case "second":
                divNum = 1000;
                break;
            case "minute":
                divNum = 1000 * 60;
                break;
            case "hour":
                divNum = 1000 * 3600;
                break;
            case "day":
                divNum = 1000 * 3600 * 24;
                break;
            default:
                break;
        }
        return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
    }
    document.write(GetDateDiff("2015/03/25 09:50:00", "2015/03/25 13:07:00", "hour"))