三次输入,包括开始时间,结束时间和两者之间的差异。
<input type="time" name="starttime" id="starttime">
<input type="time" name="endtime" id="endtime">
<input type="time" name="duration" id="duration" disabled>
当开始或结束时间改变时,差异显示在第三个输入中。
e.g。 23:15 - 20:00 = 03:15。
到目前为止,我只能生成正确的小时而不是分钟。
<script>
jQuery(document).ready(function($) {
function calculateTime() {
// Get values.
var valuestart = $("#starttime").val();
var valuestop = $("#endtime").val();
// Create date format.
var timeStart = new Date("01/01/2007 " + valuestart);
var timeEnd = new Date("01/01/2007 " + valuestop);
// Subtract.
var difference = timeEnd - timeStart;
// Attempt 1: Only gets hours.
//var difference_as_hours = difference / 60 / 60 / 1000;
//alert("Hour Difference: " + difference_as_hours);
// Attempt 2: Nothing happens.
//var difference_as_hours_and_minutes = difference.getHours() + ":" + difference.getMinutes();
//alert("Hour And Minutes Difference: " + difference_as_hours_and_minutes);
// Attempt 3: Nothing happens.
//var difference_as_date = new Date("01/01/2007 " + difference);
//var difference_as_hours_and_minutes = difference_as_date.getHours() + ":" + difference_as_date.getMinutes();
//alert("Hour And Minutes Difference: " + difference_as_hours_minutes);
// Attempt 4: Nothing happens.
var formatted_time = time_format(difference);
alert(formatted_time);
}
$("#starttime, #endtime").change(calculateTime);
calculateTime();
});
function time_format(d) {
hours = format_two_digits(d.getHours());
minutes = format_two_digits(d.getMinutes());
seconds = format_two_digits(d.getSeconds());
return hours + ":" + minutes + ":" + seconds;
}
function format_two_digits(n) {
return n < 10 ? "0" + n : n;
}
</script>
如何制作小时和分钟?
答案 0 :(得分:2)
使用momentjs检查以下工作演示:
let valuestart = moment.duration("20:00", "HH:mm");
let valuestop = moment.duration("23:15", "HH:mm");
let difference = valuestop.subtract(valuestart);
console.log(difference.hours() + ":" + difference.minutes())
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
&#13;
答案 1 :(得分:1)
你试试
function calculateTime() {
// Get values.
var valuestart = $("#starttime").val();
var valuestop = $("#endtime").val();
// Create date format.
var timeStart = new Date("01/01/2007 " + valuestart);
var timeEnd = new Date("01/01/2007 " + valuestop);
// Subtract.
var difference = timeEnd - timeStart;
var time = msToTime(difference);
console.log(time);
}
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
$("#starttime, #endtime").change(calculateTime);
答案 2 :(得分:-3)
我建议您使用moment.js,它会帮助您节省大量时间