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

时间:2017-10-23 06:26:10

标签: javascript php jquery

我目前正在使用此功能计算2个字段,结果很好但有时会丢失零。样品

10:20 + 10:30当前输出0.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);         
 }

});

当有一个无效字符时,我一直得到一个nan消息可以改为00而不是?

3 个答案:

答案 0 :(得分:2)

您可以使用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));
}

甚至更好,您可以使该功能独立于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()));

答案 1 :(得分:1)

添加功能

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

}

并在显示结果

之前调用此函数

答案 2 :(得分:0)

我建议你:

&#13;
&#13;
    $(".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;
    }
        

  
&#13;
<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>
&#13;
&#13;
&#13;