输入为“ null”。如何计算带日期的输入值?

时间:2018-07-06 22:16:47

标签: javascript html date

输入为null。如何计算带有日期的输入值?

enter image description here

/* // ========================================================
* *
* * * I Want To Calculate Input Value With Date, Input Is null
* *
*/ // ========================================================

var time     = new Date();
var realTime = time.toLocaleString();
var hours    = time.getHours();
var minutes  = time.getMinutes();

var input = document.getElementById("input");
// Value of input 20:00 => output of this input is null.

var divOfOutput = document.getElementById("output");

divOfOutput.innerHTML = (hours - input) + ":" + (minutes - input);
// Calculation Not Done, Output Just Real Time

console.log(realTime);
console.log((hours - input) + ":" + (minutes - input));
    <input id="index" type="time" value="20:00">
    <div id="output"></div>

1 个答案:

答案 0 :(得分:0)

下面的代码进行了一些基本修改,以使代码更加直观。但是,(至少对我而言)尚不完全清楚您要实现的目标。

问题已解决:

    html中的
  1. id属性,必须匹配
  2. 输入元素(DOM节点)与其内容(值)之间的差异
  3. 从输入数据中提取小时和分钟
  4. 确保只具有积极的差异

待办事项(至少):

  1. 继续进行操作,以使当前时间与输入字段中的数据之间存在有意义的差异

// Rectifying the obvious mistakes.
 
var time     = new Date();
var realTime = time.toLocaleString();
var hours    = time.getHours();
var minutes  = time.getMinutes();

var input = document.getElementById("input"); // 1. Same id attribute as in html
let a_input = input.value.split(/:/); // 2. take the value, not the element; 3. split into hours and minutes

var divOfOutput = document.getElementById("output"); 

divOfOutput.innerHTML = ((hours - a_input[0] + 24) % 24) + ":" + ((minutes - a_input[1] + 60) % 60); // 4. Make sure to have positive deltas only even when crossing midnight or the full hour


console.log(realTime);
console.log(((hours - a_input[0] + 24) % 24) + ":" + ((minutes - a_input[1] + 60) % 60));
    <input id="input" type="time" value="20:00"><!-- 1. same  id attribute as in code -->
    <div id="output"></div>