简体   繁体   English

计算后24小时输出正确的格式

[英]output correct format 24 hour after calculation

I'm currently using this function to calculate 2 fields and the results are good but sometimes missing a zero. 我目前正在使用此函数来计算2个字段,结果很好,但有时会丢失零。 sample 样品

10:20 + 10:30 current output 0.10 10:20 + 10:30电流输出0.10

10:20 + 10:30 I want the output to be 00.10 10:20 + 10:30我希望输出为00.10

$(function () {
 function calculate() {
         time1 = $("#start").val().split(':'),
         time2 = $("#end").val().split(':');
         hours1 = parseInt(time1[0], 10), 
         hours2 = parseInt(time2[0], 10),
         mins1 = parseInt(time1[1], 10),
         mins2 = parseInt(time2[1], 10);
         hours = hours2 - hours1,
         mins = 0;
     if(hours < 0) hours = 24 + hours;
     if(mins2 >= mins1) {
         mins = mins2 - mins1;
     } else {
         mins = (mins2 + 60) - mins1;
     }

     // the result
     $("#hours").val(hours + ':' + mins);         
 }

}); });

also when there is an invalid character I keep getting a nan message is possible to change this to 00 instead? 还当有无效字符时,我不断收到nan消息,可以将其改为00吗?

Instead of dealing with the strings and each value independently, you can use the javascript Date object to calculate the difference... 您可以使用javascript Date对象来计算差异,而不是单独处理字符串和每个值。

function calculate() {

    // Get time values and convert them to javascript Date objects.
    var time1 = new Date('01/01/2017 ' + $('#start').val());
    var time2 = new Date('01/01/2017 ' + $('#end').val());
    // Get the time difference in minutes. If is negative, add 24 hours.
    var hourDiff = (time2 - time1) / 60000;
    hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
    // Calculate hours and minutes.
    var hours = Math.floor(hourDiff/60);
    var minutes = Math.floor(hourDiff%60);
    // Set the result adding '0' to the left if needed        
    $("#hours").val((hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes));
}

Or even better, you can make the function independent of the DOM elements, so you can reuse it... 甚至更好的是,您可以使函数独立于DOM元素,以便您可以重用它...

function calculate(startTime,endTime) {

    // Get time values and convert them to javascript Date objects.
    var time1 = new Date('01/01/2017 ' + startTime);
    var time2 = new Date('01/01/2017 ' + endTime);
    // Get the time difference in minutes. If is negative, add 24 hours.
    var hourDiff = (time2 - time1) / 60000;
    hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
    // Calculate hours and minutes.
    var hours = Math.floor(hourDiff/60);
    var minutes = Math.floor(hourDiff%60);
    // Return the response, adding '0' to the left of each field if needed.       
    return (hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes);
}

// Now you can use the function.
$("#hours").val(calculate($('#start').val(),$('#end').val()));

Add a function 添加功能

function checkTime(i) {
if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
return i;

} }

and call this function before displaying result 并在显示结果之前调用此函数

I propose you that : 我建议你:

  $(".calculator").on("change",function(){ var isNegative = false; var hours = "00:00"; var inputStart = $("#start").val(); var inputEnd = $("#end").val(); if(inputStart!="" && inputEnd != ""){ // calculate only if the 2 fields have inputs // convert to seconds (more convenient) var seconds1 = stringToSeconds(inputStart); var seconds2 = stringToSeconds(inputEnd); var secondsDiff = seconds2 - seconds1; var milliDiffs = secondsDiff * 1000; if(milliDiffs < 0){ milliDiffs = milliDiffs *-1; isNegative = true; } // Convert the difference to date var diff = new Date(milliDiffs); // convert the date to string hours = diff.toUTCString(); // extract the time information in the string 00:00:00 var regex = new RegExp(/[0-9]{2}:[0-9]{2}:[0-9]{2}/); var arr = hours.match(regex); hours = arr[0]; // Take only hours and minutes and leave the seconds arr = hours.split(":"); hours=arr[0]+":"+arr[1]; // put minus in front if negative if(isNegative){ hours = "-"+hours; } // Show the result $("#hours").val(hours); // Put back the inputs times in case there were somehow wrong // (it's the same process) var date1 = new Date(seconds1*1000); var str1 = date1.toUTCString(); arr = str1.match(regex); hours = arr[0]; arr = hours.split(":"); hours=arr[0]+":"+arr[1]; $("#start").val(hours); // idem for time 2 var date2 = new Date(seconds2*1000); var str2 = date2.toUTCString(); arr = str2.match(regex); hours = arr[0]; arr = hours.split(":"); hours=arr[0]+":"+arr[1]; $("#end").val(hours); } }); function timeElementToString(timeElement){ var output = timeElement.toString(); if(timeElement < 10 && timeElement >=0) output = "0"+output; else if(timeElement < 0 && timeElement >=-10) output = "-0"+Math.abs(output); return output; } function stringToSeconds(input){ var hours = 0; var arr=input.split(":"); if(arr.length==2){ hours=parseInt(arr[0]); minutes=parseInt(arr[1]); if(isNaN(hours)){ hours = 0; } if(isNaN(minutes)){ minutes = 0; } } return hours*3600+60*minutes; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <label for="start">Start</label><input type="text" id="start" class="calculator"></input><br /> <label for="end">End</label><input type="text" id="end" class="calculator"></input><br /> <label for="hours">Hours</label><input type="text" id="hours" readonly="readonly"></input> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM