Javascript 如何计算 24 小时格式的两个时间之间的差异?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11038252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:09:54  来源:igfitidea点击:

How can I calculate the difference between two times that are in 24 hour format?

javascriptjqueryhtml

提问by CyberJunkie

In JavaScript, how can I calculate the difference between two times that are in 24 hour format?

在 JavaScript 中,如何计算 24 小时格式的两个时间之间的差异?

Example: Get how many hours elapsed from 08:00:00to 23:00:00.

示例:获取从08:00:00到过去的小时数23:00:00

Below I'm getting two time values from two dropdown menus and trying to calculate the difference in hours between the two times. I get wrong results...

下面我从两个下拉菜单中获取两个时间值,并尝试计算两个时间之间的小时差。我得到错误的结果...

Working example: http://jsfiddle.net/VnwF7/1/

工作示例:http: //jsfiddle.net/VnwF7/1/

Script:

脚本:

$(document).ready(function() {
    function calculateTime() {
             //get values
        var valuestart = $("select[name='timestart']").val();
        var valuestop = $("select[name='timestop']").val();

             //create date format       
        var timeStart = new Date("01/01/2007 " + valuestart);
        var timeEnd = new Date("01/01/2007 " + valuestop);

        var difference = timeEnd - timeStart;            
        var diff_result = new Date(difference);    

        var hourDiff = diff_result.getHours();

        $("p").html("<b>Total Hours:</b> " + hourDiff )          
    }
    $("select").change(calculateTime);
    calculateTime();
});

HTML:

HTML:

<select name="timestart">
<option value="00:00:00">12:00 am</option>
<option value="01:00:00">1:00 am</option>
<option value="02:00:00">2:00 am</option>
<option value="03:00:00">3:00 am</option>
<option value="04:00:00">4:00 am</option>
<option value="05:00:00">5:00 am</option>
<option value="06:00:00">6:00 am</option>
<option value="07:00:00">7:00 am</option>
<option value="08:00:00">8:00 am</option>
<option value="09:00:00">9:00 am</option>
<option value="10:00:00">10:00 am</option>
<option value="11:00:00">11:00 am</option>
<option value="12:00:00">12:00 pm</option>
<option value="13:00:00">1:00 pm</option>
<option value="14:00:00">2:00 pm</option>
<option value="15:00:00">3:00 pm</option>
<option value="16:00:00">4:00 pm</option>
<option value="17:00:00">5:00 pm</option>
<option value="18:00:00">6:00 pm</option>
<option value="19:00:00">7:00 pm</option>
<option value="20:00:00">8:00 pm</option>
<option value="21:00:00">9:00 pm</option>
<option value="22:00:00">10:00 pm</option>
<option value="23:00:00">11:00 pm</option>
</select>

<select name="timestop">
<option value="00:00:00">12:00 am</option>
<option value="01:00:00">1:00 am</option>
<option value="02:00:00">2:00 am</option>
<option value="03:00:00">3:00 am</option>
<option value="04:00:00">4:00 am</option>
<option value="05:00:00">5:00 am</option>
<option value="06:00:00">6:00 am</option>
<option value="07:00:00">7:00 am</option>
<option value="08:00:00">8:00 am</option>
<option value="09:00:00">9:00 am</option>
<option value="10:00:00">10:00 am</option>
<option value="11:00:00">11:00 am</option>
<option value="12:00:00">12:00 pm</option>
<option value="13:00:00">1:00 pm</option>
<option value="14:00:00">2:00 pm</option>
<option value="15:00:00">3:00 pm</option>
<option value="16:00:00">4:00 pm</option>
<option value="17:00:00">5:00 pm</option>
<option value="18:00:00">6:00 pm</option>
<option value="19:00:00">7:00 pm</option>
<option value="20:00:00">8:00 pm</option>
<option value="21:00:00">9:00 pm</option>
<option value="22:00:00">10:00 pm</option>
<option value="23:00:00">11:00 pm</option>
</select>

<p></p>

回答by ?????

You can just subtract the hours right away doing it this way

您可以通过这种方式立即减去小时数

var valuestart = $("select[name='timestart']").val();
var valuestop = $("select[name='timestop']").val();

//create date format          
var timeStart = new Date("01/01/2007 " + valuestart).getHours();
var timeEnd = new Date("01/01/2007 " + valuestop).getHours();

var hourDiff = timeEnd - timeStart;             

Here's the working fiddle http://jsfiddle.net/VnwF7/4/

这是工作小提琴http://jsfiddle.net/VnwF7/4/

UPDATE - to calculate if we are including the next day. Just add the following if block

更新 - 计算我们是否包括第二天。只需添加以下 if 块

 if (hourDiff < 0) {
    hourDiff = 24 + hourDiff;
 }

http://jsfiddle.net/gfvhqat9/

http://jsfiddle.net/gfvhqat9/

回答by peacemaker

I changed your code to just use the difference without having to create another date object:

我将您的代码更改为仅使用差异而无需创建另一个日期对象:

$(document).ready(function() {    
function calculateTime() {
        //get values
        var valuestart = $("select[name='timestart']").val();
        var valuestop = $("select[name='timestop']").val();

         //create date format          
         var timeStart = new Date("01/01/2007 " + valuestart);
         var timeEnd = new Date("01/01/2007 " + valuestop);

         var difference = timeEnd - timeStart;             

         difference = difference / 60 / 60 / 1000;


    $("p").html("<b>Hour Difference:</b> " + difference)             

}
$("select").change(calculateTime);
calculateTime();
});?

回答by silverfighter

It is not Jquery but everything related to time and date in JavaScript...

它不是 Jquery,而是 JavaScript 中与时间和日期相关的所有内容......

This might help: datejs http://code.google.com/p/datejs/

这可能会有所帮助:datejs http://code.google.com/p/datejs/

Here is some date and time calculation from the docs

这是文档中的一些日期和时间计算

 Date.today().set({ day: 15 }) ? ? ? ? ?// Sets the day to the 15th of the current month and year. Other object values include year|month|day|hour|minute|second.

? ? ? ? Date.today().set({ year: 2007, month: 1, day: 20 })


Date.today().add({ days: 2 }) ? ? ? ? ?// Adds 2 days to the Date. Other object values include year|month|day|hour|minute|second.

? ? ? ? Date.today().add({ years: -1, months: 6, hours: 3 })


Date.today().addYears(1) ? ? ? ? ? ? ? // Add 1 year.
Date.today().addMonths(-2) ? ? ? ? ? ? // Subtract 2 months.
Date.today().addWeeks(1) ? ? ? ? ? ? ? // Add 1 week
Date.today().addHours(6) ? ? ? ? ? ? ? // Add 6 hours.
Date.today().addMinutes(-30) ? ? ? ? ? // Subtract 30 minutes
Date.today().addSeconds(15) ? ? ? ? ? ?// Add 15 seconds.
Date.today().addMilliseconds(200) ? ? ?// Add 200 milliseconds.

Date.today().moveToFirstDayOfMonth() ? // Returns the first day of the current month.
Date.today().moveToLastDayOfMonth() ? ?// Returns the last day of the current month.

new Date().clearTime() ? ? ? ? ? ? ? ? // Sets the time to 00:00 (start of the day).
Date.today().setTimeToNow() ? ? ? ? ? ?// Resets the time to the current time (now). The functional opposite of .clearTime()

EDIT:Since this is a rather old answer I lately do also use moment.js for date related operations really useful, too. http://momentjs.com/https://github.com/moment/moment/

编辑:由于这是一个相当古老的答案,我最近也将 moment.js 用于与日期相关的操作,这也非常有用。 http://momentjs.com/ https://github.com/moment/moment/

回答by Prasenjit Kumar Nag

You dont need to convert them into dates for this specific case. Just Do this

对于这种特定情况,您不需要将它们转换为日期。就这样做

$(document).ready(function() {    
    function calculateTime() { 
        var hourDiff = 
        parseInt($("select[name='timestart']").val().split(':')[0],10) -         
        parseInt($("select[name='timestop']").val().split(':')[0],10);

        $("p").html("<b>Hour Difference:</b> " + hourDiff )         
    }
    $("select").change(calculateTime);
    calculateTime();
});

Working fiddle?

工作小提琴

回答by Pradeep Saini

try this way

试试这个方法

var time_start = new Date();
var time_end = new Date();
var value_start = "06:00:00".split(':');
var value_end = "23:00:00".split(':');

time_start.setHours(value_start[0], value_start[1], value_start[2], 0)
time_end.setHours(value_end[0], value_end[1], value_end[2], 0)

time_end - time_start // millisecond