javascript 计算javascript中两个日期时间之间的持续时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21554603/
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-10-27 21:09:42  来源:igfitidea点击:

Calculate duration between two date times in javascript

javascriptdatetime

提问by user2247744

I need to calculate the duration between two datetimes in JavaScript. I have tried this code:

我需要计算 JavaScript 中两个日期时间之间的持续时间。我试过这个代码:

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!

var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = mm+'/'+dd+'/'+yyyy;  //Current Date
console.log("current date"+today);


var valuestart ="8:00 AM";
var valuestop = "4:00 PM";//$("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;             
console.log("duration"+hourDiff);

From this, I am able to get Current Date and duration. But when I replace the date "01/01/2007" with the variable "today", I am getting the result as NaN. Please guide me in where I am wrong. Thanks in advance.

由此,我可以获得当前日期和持续时间。但是当我用变量“今天”替换日期“01/01/2007”时,我得到的结果为 NaN。请指导我在哪里我错了。提前致谢。

采纳答案by Jér?me Teisseire

Try this :

试试这个 :

        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!

        var yyyy = today.getFullYear();
        if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = dd+'/'+mm+'/'+yyyy;  //Current Date

        var valuestart ="8:00 AM";
        var valuestop = "4:00 PM";//$("select[name='timestop']").val();

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

        var hourDiff = timeEnd - timeStart;  
        alert("duration:"+hourDiff);

回答by Christophe Roussy

You should work on the epoch milliseconds. The idea is to transform everything to the epoch millis representation, perform your calculations, then go back to another format if needed.

您应该在 epoch 毫秒上工作。这个想法是将所有内容转换为纪元毫秒表示,执行计算,然后根据需要返回另一种格式。

There are many articles on the subject:

有很多关于这个主题的文章:

回答by KJ Price

today is of Date type whereas "01/01/2007" is a string. Trying to concatenate a Date object with "8:00 AM" will not work. You will have to turn today variable into a string or use today.setHours(8)

今天是日期类型,而“01/01/2007”是一个字符串。尝试将 Date 对象与“8:00 AM”连接起来是行不通的。您必须将 today 变量转换为字符串或使用 today.setHours(8)