我从用户那里得到两个持续时间current time
和previous time
。现在,我想计算在第三个文本框中显示它的总时间。
<p><span>Current Duration</span><input id="txt1" onblur="sum();" type="text" autocomplete="off" name="current_duration" value="" /></p>
<p><span>Previous Duration</span><input id="txt2" onblur="sum();" type="text" autocomplete="off" name="previous_duration" value="" /></p>
<p><span>Total Duration</span><input id="txt3" type="text" readonly autocomplete="off" name="total_duration" value="" /></p>
<script>
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
</script>
我如何实现相同的目标?你能帮助我吗?
答案 0 :(得分:1)
我从SO.
找到了这个你可以试试这个:
function sum()
{
var datetime = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var datetime = new Date(datetime).getTime();
var now = new Date(txtSecondNumberValue).getTime();
if( isNaN(datetime) )
{
return "";
}
console.log( datetime + " " + now);
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var date_diff = new Date( milisec_diff );
return days + "d "+ (date_diff.getHours() - 5) + "h " + (date_diff.getMinutes() - 30) + "m";
}
答案 1 :(得分:1)
在时间和分钟之间确定分隔符为'。',这将起作用。如果我需要另一个分隔符,只需替换toTime()和fromTime()
中的字符<p><span>Current Duration</span><input id="txt1" onblur="sum();" type="text" autocomplete="off" name="current_duration" value="" /></p>
<p><span>Previous Duration</span><input id="txt2" onblur="sum();" type="text" autocomplete="off" name="previous_duration" value="" /></p>
<p><span>Total Duration</span><input id="txt3" type="text" readonly autocomplete="off" name="total_duration" value="" /></p>
<script>
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = fromTime(txtFirstNumberValue) + fromTime(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = toTime(result);
}
}
function fromTime(time) {
var timeArray = time.split('.');
var hours = parseInt(timeArray[0]);
var minutes = parseInt(timeArray[1]);
return (hours * 60) + minutes;
}
function toTime(number) {
var hours = Math.floor(number / 60);
var minutes = number % 60;
return hours + "." + (minutes <= 9 ? "0" : "") + minutes;
}
</script>