12

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

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

谢谢!

4

12 回答 12

45

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

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;
}

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

于 2012-05-29T18:04:55.973 回答
3

试试这个

var dif = ( new Date("1970-1-1 " + end-time) - new Date("1970-1-1 " + start-time) ) / 1000 / 60 / 60;
于 2014-12-15T12:33:05.827 回答
1

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

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

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

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

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);
}

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

在与我的朋友一起改进和大量脑力之后,我们得出了这个结论:

$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.

因此,您实际上只需要 4 行代码即可获得结果。您可以只花几分钟或显示全时(例如差异是 02:32)2 小时 32 分钟。最重要的是:您仍然可以按 24 小时制计算过夜,也就是:开始时间晚上 11:50 到上午 1:00(24 小时制 23:50 - 01:00),因为在 12 小时模式下它仍然有效。

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

于 2013-09-04T11:19:13.910 回答
1

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

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;
}

我的更新版本:

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

示例 - 年/月/周/日/小时/分钟/秒

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

于 2016-03-08T11:51:03.850 回答
1

您提供的秒数对我没有结果,请在此处找到我的更新功能,为您提供正确的秒数-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;
}
于 2017-09-09T12:27:59.717 回答
1

tl;博士

一关

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

作为一个函数

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

解释

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

于 2020-01-17T18:34:16.897 回答
1

此解决方案适用于计算不同军事时间之间的差异

示例格式:开始 = 23:00 / 结束 = 02:30

function diff(start, end) {
start = start.split(":");
end = end.split(":");
if(Number(start[0]) > Number(end[0]) ) {
  var num = Number(start[0])
  var countTo = Number(end[0]);
  var count = 0;
  for (var i = 1; num != countTo;) {
    num = num + i
    if(num > 24) {
      num = 0
    }
    count++
  }
  var hours = count - 1;
  var startDate = new Date(0, 0, 0, start[0], start[1], 0);
  var endDate = new Date(0, 0, 0, end[0], end[1], 0);
  if(startDate.getMinutes() > endDate.getMinutes()) {
    var hours = count - 2;
    var diff = 60 - (startDate.getMinutes() - endDate.getMinutes());      
  } else {
    var diff = endDate.getMinutes() - startDate.getMinutes();      
  }
  var minutes = diff
} else {
  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);
}

var returnValue = (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes

return returnValue;

}

于 2020-10-22T20:21:01.970 回答
0

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

注意:这不是使用日期对象或 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">

于 2018-04-06T14:12:30.010 回答
0
   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);
}
于 2018-07-25T08:30:09.937 回答
0

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;
} 

于 2019-06-14T12:10:29.187 回答
-1

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

我以这种方式解决了它。

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

这是我的代码。

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(":"));
    }
});
于 2015-09-24T09:17:23.277 回答
-2

我们通常需要时间差来估计 I/O 操作、SP 调用等所花费的时间,NodeJs 最简单的解决方案(控制台在回调-异步执行)如下:

var startTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01

callYourExpectedFunction(param1, param2, function(err, result){
    var endTime = new Date().getTime();
    //This will give you current time in milliseconds since 1970-01-01

    console.log(endTime  - startTime)
    //This will give you time taken in milliseconds by your function

   if(err){
   }
   else{
   }
})
于 2018-02-02T06:03:43.997 回答