JavaScript在两个日期和时间之间的小时数差异

问题描述:

我的html文件中有三个类型为text的输入字段.

I have three input fields of type text in my html file.

  1. 第一个输入字段称为OLD DATE&时间.
  2. 第二个输入字段称为NEW DATE&.时间.
  3. 第三输入字段称为小时差异.

我想要的是:

  • 如果用户输入第一个输入字段(旧日期和时间),然后输入第二个输入字段(新日期和时间),则第三个输入字段必须自动仅显示小时数差异在第二个输入字段后填充日期&时间和松散焦点(onBlur).
  • 如果第二个输入(新日期和时间)或第一个输入(旧日期和时间)为空,则第三个输入(小时数差异)将不会给出答案.
  • if a user enters the first input field (old date & time) and then enters the second input field (new date & time), the third input field must show the difference in hours automatically only after the second input field filled with date & time and loose focus (onBlur).
  • The third input (difference in hours) will not give answer if the second input (new date & time) or the first input (old date & time) is empty.

在第一个输入和第二个输入上有一个 datetime picker (日期时间选择器),我将感到非常高兴.

And I would be very delighted to have a datetime picker on the first and second input.

这是代码:

<label>OLD DATE & TIME: </label>
<input id="old" type="datetime-local" name="old" />
<p>
    <label>NEW DATE & TIME: </label>
    <input id="new" type="datetime-local" name="new" onBlur="document.getElementById('total').value = (new Date(this.value) - new Date(old.value))/(1000*60*60)" />
<p>
<label>DIFFERENCE IN HOURS :</label>
<br>
<input id="total" type="text" name="total" onChange="changeDate()" />

我知道Firefox和Internet Explorer不支持输入类型= datetime-local,所以我想使用输入类型的文本,但它总是给我NaN.

i know firefox and internet explores does not support input type =datetime-local, so i want to use input type text but it always give me NaN.

如果要使用纯JavaScript,则可以通过这种方式进行计算.

If you want to use plain javascript then you can do calculations in this way..

    var fromDate = parseInt(new Date(oldDate).getTime()/1000); 
    var toDate = parseInt(new Date(newDate).getTime()/1000);
    var timeDiff = (toDate - fromDate)/3600;  // will give difference in hrs