Sil*_*ine 2 javascript jquery datetime momentjs
我试图获得两个日期时间本地输入(开始和结束日期)之间的小时数差异。我正在尝试用 momentjs 库来做但没有成功。我知道问题出在日期时间本地输入的格式上,但是,有什么方法可以对其进行格式化以允许 Momentjs 获取并进行比较?或者我应该尝试使用不同的库/输入?
<input type="datetime-local" name="input-time" id="start-time">
<input id="end-time" type="datetime-local" onchange="myFunction()">
<input type="text" id="total-hours" placeholder="Total Hours">
function myFunction() {
var initialTime=document.getElementById("start-time");
var initialTimeFormat=moment(initialTime);
var endTime=document.getElementById("end-time");
var endTimeFormat=moment(endTime);
var totalHours=endTimeFormat.diff(initialTimeFormat,"hours");
$("#total-hours").text(totalHours);
}
Run Code Online (Sandbox Code Playgroud)
我总是喜欢香草选项,因为您只使用小时,所以我们可以不用库,例如时刻。然而,它是一个用于比较日期等的好库。
正如其他答案中所说,真正的问题在于值的检索:
$("input#start-time").val()); //retrieving using jQuery.
document.getElementById("start-time").value; //retrieving using vanilla. | old
document.querySelector("#start-time").value; //retrieving using vanilla. | modern
Run Code Online (Sandbox Code Playgroud)
此外,不建议使用内联事件。使用addEventListener.
$("input#start-time").val()); //retrieving using jQuery.
document.getElementById("start-time").value; //retrieving using vanilla. | old
document.querySelector("#start-time").value; //retrieving using vanilla. | modern
Run Code Online (Sandbox Code Playgroud)
document.querySelector("#end-time").addEventListener("change", myFunction);
function myFunction() {
function split(time)
{
var t = time.split(":");
return parseInt((t[0] * 60), 10) + parseInt(t[1], 10); //convert to minutes and add minutes
}
//value start
var start = split($("input#start-time").val()); //format HH:MM
//value end
var end = split($("input#end-time").val()); //format HH:MM
totalHours = NaN;
if (start < end)
{
totalHours = Math.floor((end-start)/60);
}
$("#total-hours").val(totalHours);
}Run Code Online (Sandbox Code Playgroud)
带有日期选择器(Chrome、Firefox 和 Edge)。这里我们使用时间戳进行比较。获取两个时间戳Date.parse。由于输入datetime-local总是会给我们一个正确格式化的 ISO 日期。减去时间戳给我们以毫秒为单位的差异。一些基本的划分给我们留下了小时数。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input-time" id="start-time" placeholder="HH:MM">
<input id="end-time" type="text" placeholder="HH:MM" >
<input type="text" id="total-hours" placeholder="Total Hours">Run Code Online (Sandbox Code Playgroud)
document.querySelector("#end-time").addEventListener("change", myFunction);
function myFunction() {
//value start
var start = Date.parse($("input#start-time").val()); //get timestamp
//value end
var end = Date.parse($("input#end-time").val()); //get timestamp
totalHours = NaN;
if (start < end) {
totalHours = Math.floor((end - start) / 1000 / 60 / 60); //milliseconds: /1000 / 60 / 60
}
$("#total-hours").val(totalHours);
}Run Code Online (Sandbox Code Playgroud)