gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:01:08 26 4
gpt4 key购买 nike

我目前正在使用此函数计算 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?

最佳答案

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

关于javascript - 计算后24小时输出正确格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46883149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com