用 JavaScript 计算时差

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

Calculate Time Difference with JavaScript

javascripttime

提问by user1424332

I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.

我有两个 HTML 输入框,需要计算 JavaScript onBlur 中的时间差(因为我需要实时)并将结果插入到新的输入框中。

Format example: 10:00 & 12:30 need to give me: 02:30

格式示例:10:00 & 12:30 需要给我:02:30

Thanks!

谢谢!

回答by VisioN

Here is one possible solution:

这是一种可能的解决方案:

function diff(start, end) {
    start = start.split(":");
    end = end.split(":");
    var startDate = new Date(0, 0, 0, start[0], start[1], 0);
    var endDate = new Date(0, 0, 0, end[0], end[1], 0);
    var diff = endDate.getTime() - startDate.getTime();
    var hours = Math.floor(diff / 1000 / 60 / 60);
    diff -= hours * 1000 * 60 * 60;
    var minutes = Math.floor(diff / 1000 / 60);

    // If using time pickers with 24 hours format, add the below line get exact hours
    if (hours < 0)
       hours = hours + 24;

    return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}

DEMO:http://jsfiddle.net/KQQqp/

演示:http : //jsfiddle.net/KQQqp/

回答by Germo

Well this work almost great. Now use this code to calculate: 23:50 - 00:10 And see what you get.Or even 23:30 - 01:30. That's a mess. Because getting the answer the other way in php is:

好吧,这项工作几乎很棒。现在使用此代码计算: 23:50 - 00:10 看看你得到了什么。甚至 23:30 - 01:30。那是一团糟。因为在 php 中以另一种方式获得答案是:

$date1 = strtotime($_POST['started']);
$date2 = strtotime($_POST['ended']);
$interval = $date2 - $date1;
$playedtime = $interval / 60;

But still, it works like yours. I guess have to bring in the dates aswell?

但是,它仍然像您一样工作。我想还必须带上日期吗?

And again: My hard research and development helped me.

再说一遍:我的努力研究和开发帮助了我。

if (isset($_POST['calculate'])) {
$d1 = $_POST['started'];
$d2 = $_POST['ended'];
if ($d2 < $d1) {
    $date22 = date('Y-m-');
    $date222 = date('d')-1;
    $date2 = $date22."".$date222;
} else {
$date2 = date('Y-m-d');
}
$date1 = date('Y-m-d');
$start_time = strtotime($date2.' '.$d1);
$end_time = strtotime($date1.' '.$d2); // or use date('Y-m-d H:i:s') for current time
$playedtime = round(abs($start_time - $end_time) / 60,2);
}

And that's how you calculate time over to the next day. //edit. First i had date1 jnd date2 switched. I need to -1 because this calculation only comes on next day and the first date vas yesterday.

这就是你如何计算到第二天的时间。//编辑。首先,我切换了 date1 jnd date2。我需要 -1 因为这个计算只出现在第二天和昨天的第一个日期。

After improving and a lot of brain power with my friend we came up to this:

在与我的朋友一起改进和大量脑力之后,我们想到了这个:

$begin=mktime(substr($_GET["start"], 0,2),substr($_GET["start"], 2,2),0,1,2,2003);
$end=mktime(substr($_GET["end"], 0,2),substr($_GET["end"], 2,2),0,1,3,2003);
$outcome=($end-$begin)-date("Z");
$minutes=date("i",$outcome)+date("H",$outcome)*60; //Echo minutes only
$hours = date("H:i", $outcome); //Echo time in hours + minutes like 01:10 or something.

So you actually need only 4 lines of code to get your result. You can take only minutes or show full time (like difference is 02:32) 2 hours and 32 minutes. What's most important: Still you can calculate overnight in 24 hour clock aka: Start time 11:50PM to let's say 01:00 AM (in 24 hour clock 23:50 - 01:00) because in 12 hour mode it works anyway.

所以你实际上只需要 4 行代码就可以得到你的结果。您可以只花几分钟或显示全时(例如差异是 02:32)2 小时 32 分钟。最重要的是:您仍然可以在 24 小时制中计算过夜,又名:开始时间 11:50PM 到上午 01:00(在 24 小时制中为 23:50 - 01:00),因为在 12 小时模式下它无论如何都可以工作。

What's most important: You don't have to format your input. You can use just plain 2300 as 23:00 input. This script will convert text field input to correct format by itself. Last script uses standard html form with method="get" but you can convert it to use POST method as well.

最重要的是:您不必格式化输入。您可以仅使用普通的 2300 作为 23:00 输入。此脚本将自行将文本字段输入转换为正确的格式。最后一个脚本使用带有 method="get" 的标准 html 表单,但您也可以将其转换为使用 POST 方法。

回答by xDemonsxXxSaintx

This is an updated version of one that was already submitted. It is with the seconds.

这是已经提交的版本的更新版本。它与秒。

function diff(start, end) {
    start = start.split(":");
    end = end.split(":");
    var startDate = new Date(0, 0, 0, start[0], start[1], 0);
    var endDate = new Date(0, 0, 0, end[0], end[1], 0);
    var diff = endDate.getTime() - startDate.getTime();
    var hours = Math.floor(diff / 1000 / 60 / 60);
    diff -= hours * (1000 * 60 * 60);
    var minutes = Math.floor(diff / 1000 / 60);
    diff -= minutes * (1000 * 60);
    var seconds = Math.floor(diff / 1000);

    // If using time pickers with 24 hours format, add the below line get exact hours
    if (hours < 0)
       hours = hours + 24;

    return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes + (seconds<= 9 ? "0" : "") + seconds;
}

My Updated Version:

我的更新版本:

Allows for you to convert the dates into milliseconds and go off of that instead of splitting.

允许您将日期转换为毫秒,然后关闭而不是拆分。

Example Does -- Years/Months/Weeks/Days/Hours/Minutes/Seconds

示例是否 - 年/月/周/天/小时/分钟/秒

Example: https://jsfiddle.net/jff7ncyk/308/

示例:https: //jsfiddle.net/jff7ncyk/308/

回答by user8584085

With seconds you provided is not get result to me please find my updated function giving you the correct seconds here - By Dinesh J

您提供的秒数对我来说没有得到结果,请在此处找到我更新的函数,为您提供正确的秒数 - 作者 Dinesh J

function diff(start, end) {
    start = start.split(":");
    end = end.split(":");
    var startDate = new Date(0, 0, 0, start[0], start[1],start[2], 0);
    var endDate = new Date(0, 0, 0, end[0], end[1],end[2], 0);
    var diff = endDate.getTime() - startDate.getTime();
    var hours = Math.floor(diff / 1000 / 60 / 60);
    diff -= hours * 1000 * 60 * 60;
    var minutes = Math.floor(diff / 1000 / 60);
    var seconds = Math.floor(diff / 1000)-120;

    // If using time pickers with 24 hours format, add the below line get exact hours
    if (hours < 0)
        hours = hours + 24;

    return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes+ ":" + (seconds <= 9 ? "0" : "") + seconds;
}

回答by Abhishek Motiwale

Try This

尝试这个

var dif = ( new Date("1970-1-1 " + end-time) - new Date("1970-1-1 " + start-time) ) / 1000 / 60 / 60;

回答by mplungjan

Depending on what you allow to enter, this one will work. There may be some boundary issues if you want to allow 1am to 1pm

根据您允许输入的内容,这将起作用。如果你想允许凌晨 1 点到下午 1 点,可能会有一些边界问题

NOTE: This is NOT using a date objects or moment.js

注意:这不是使用日期对象或 moment.js

function pad(num) {
  return ("0"+num).slice(-2);
}
function diffTime(start,end) {
  var s = start.split(":"), sMin = +s[1] + s[0]*60,
      e =   end.split(":"), eMin = +e[1] + e[0]*60,
   diff = eMin-sMin;
  if (diff<0) { sMin-=12*60;  diff = eMin-sMin }
  var h = Math.floor(diff / 60),
      m = diff % 60;
  return "" + pad(h) + ":" + pad(m);
}  
document.getElementById('button').onclick=function() {
  document.getElementById('delay').value=diffTime(
      document.getElementById('timeOfCall').value, 
      document.getElementById('timeOfResponse').value
  );
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">

回答by Sanket Parchande

   calTimeDifference(){
    this.start = dailyattendance.InTime.split(":");
    this.end = dailyattendance.OutTime.split(":");
    var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
    var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
    var time3 = ((time2 - time1) / 60);
    var timeHr = parseInt(""+time3);
    var  timeMin = ((time2 - time1) % 60);
}

回答by Shanshana Samarajeewa

TimeCount = function()
{
    t++;
    var ms = t;
    if (ms == 99)
    {
        s++;
        t = 0;
        if ( s == 60)
        {
            m++;
            s = 0;
        }
    }

    Dis_ms = checkTime(ms);
    Dis_s = checkTime(s);
    Dis_m = checkTime(m);
    
    document.getElementById("time_val").innerHTML = Dis_m + ":" + Dis_s+ ":" + Dis_ms;
}

function checkTime(i) 
{
  if (i<10) {
    i = "0" + i;
  }
  return i;
} 

回答by MetaSean

tl;dr

tl;博士

One off run

一关

const t1 = new Date(1579876543210) // your initial time
const t2 = new Date(1579987654321) // your later time

const diff = t2-t1
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const humanDiff = `${Math.floor(diff/HRS)}:${Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})}:${Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})}.${Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})}`

console.log("humanDiff:", humanDiff)
// > humanDiff: 30:51:51.0111

As a function

作为函数

function humanDiff (t1, t2) {
  const diff = Math.max(t1,t2) - Math.min(t1,t2) 
  const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
  
  const hrs = Math.floor(diff/HRS)
  const min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
  const sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
  const ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
  
  return `${hrs}:${min}:${sec}.${ms}`
}

const t1 = new Date(1579876543210)
const t2 = new Date(1579987654321)

console.log("humanDiff(t1, t2):", humanDiff(t1, t2))
// > humanDiff: 30:51:51.0111

Explanation

解释

Adjust humanDifffor your maximum and minimum reportable increments and formatting needs:

调整humanDiff你的最大和最小报告增量和格式化的需求:

const t1 = new Date(1579876543210) // Set your initial time (`t1`)
const t2 = new Date(1579986654321) // , conclusion time (`t2`), and
const diff = t2-t1 // calculate their difference in milliseconds
console.log("         t2:", t2.toISOString()) // >   t2: 2020-01-25T21:27:34.321Z
console.log("         t1:", t1.toISOString()) // >   t1: 2020-01-24T14:35:43.210Z
console.log("       diff:", diff)             // > diff: 111111111

// Set your constant time values for easy readability
const SEC = 1000
const MIN = 60 * SEC
const HRS = 60 * MIN

/* For a given unit
1) disregard any previously relevant units, e.g. to calculate minutes, we can
   disregard all hours & focus on only the remainder - `(diff%HRS)`
2) divide the remainder by the given unit, e.g. for minutes, `(diff%HRS)/MIN`
3) disregard any remainder, e.g. again for minutes, `Math.floor((diff%HRS)/MIN)`
NOTE: for your maximum unit (HRS in the examples below) you probably _don't_
  want to disregard high values, e.g. If the difference is >24 hrs and something,
  you should either include a DAYS value, or simply display 30 hrs */
let hrs = Math.floor(diff/HRS)
let min = Math.floor((diff%HRS)/MIN)
let sec = Math.floor((diff%MIN)/SEC)
let ms  = Math.floor(diff % SEC) // just the remainder 
          // BUT ms IS NOT ACTUALLY CORRECT, see humanDiff_3 for the fix ;-)
let humanDiff_1 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_1:", humanDiff_1)
// > humanDiff_1: 30:51:51.111

sec = Math.round((diff%MIN)/SEC) // can also just round the last unit
const humanDiff_2 = `${hrs} hrs ${min} mins & ${sec} secs`
console.log("humanDiff_2:", humanDiff_2)
// > humanDiff_2: 30 hrs 51 mins & 51 secs

/* To ensure a set number of digits, format the numbers with `toLocaleString`'s
   `minimumIntegerDigits`, if more than 3 digits, also use its `useGrouping`   */
hrs = Math.floor(diff/HRS)
min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})

const humanDiff_3 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_3:", humanDiff_3)
// > humanDiff_3: 30:51:51.0111
// NOTE: milliseconds are now 4 digits

回答by user5371360

Try this: actually this a problem from codeeval.com

试试这个:实际上这是来自 codeeval.com 的问题

I solved it in this way .

我是这样解决的。

This program takes a file as the argument so i used a little node js to read the file.

该程序将文件作为参数,因此我使用了一个小节点 js 来读取文件。

Here is my code.

这是我的代码。

var fs  = require("fs");
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
    if (line !== "") {
        var arr = line.split(" ");
        var arr1 = arr[0].split(":");
        var arr2 = arr[1].split(":");
        var time1 = parseInt(arr1[0])*3600 + parseInt(arr1[1])*60 + parseInt(arr1[2]);
        var time2 = parseInt(arr2[0])*3600 + parseInt(arr2[1])*60 + parseInt(arr2[2]);
        var dif = Math.max(time1,time2) - Math.min(time1,time2);
        var ans = [];
        ans[0] = Math.floor(dif/3600);
        if(ans[0]<10){ans[0] = "0"+ans[0]}
        dif = dif%3600;
        ans[1] = Math.floor(dif/60);
        if(ans[1]<10){ans[1] = "0"+ans[1]}
        ans[2] = dif%60;
        if(ans[2]<10){ans[2] = "0"+ans[2]}
        console.log(ans.join(":"));
    }
});