JS关于使用2个功能比较日期的问题

时间:2019-03-17 13:08:28

标签: javascript

嗨,我是Java语言的新手,因此很抱歉提出naff问题。 这段代码在应检索已过去的天数时返回Nan。 第二个功能是否引起了问题?

这里是:

<body>
  <script>
    function elapsedTime(date1, date2) {
      var start = new Date(date1);
      var startMilli = start.getTime();

      var end = new Date(date2);
      var endMilli = end.getTime();

      var elapsed = (endMilli - startMilli);
      alert(millisToDaysHoursMinutes(elapsed));

    }
    function millisToDaysHoursMinutes(millis) {
      var seconds = millis / 1000;
      var totalMinutes = seconds / 60;
      var minutesPerDay = 60 * 24;
      var days  = totalMinutes / minutesPerDay;

      return days;
    }
  </script>
  <form>
    Start:<input type="text" name="date1" value="dd/m/year" /><br>
    End:  <input type="text" name="date2" value="dd/m/year" />
    <input type="button" name="button1" onclick="elapsedTime(date1.value, date2.value)" value="Get Elapsed Time" />
  </form>
</body>

2 个答案:

答案 0 :(得分:0)

您需要确保输入的日期有效,否则您将得到days(不是数字)。使用NaN并将其设置为input type=date,然后可以在调用日期差异函数之前轻松地检查它们是否有效。

EG:

required
function elapsedTime(date1, date2) {
  var start = new Date(date1);
  var startMilli = start.getTime();

  var end = new Date(date2);
  var endMilli = end.getTime();

  var elapsed = (endMilli - startMilli);
  alert(millisToDaysHoursMinutes(elapsed));

}

function millisToDaysHoursMinutes(millis) {
  var seconds = millis / 1000;
  var totalMinutes = seconds / 60;
  var minutesPerDay = 60 * 24;
  var days = totalMinutes / minutesPerDay;

  return days;
}
var date1 = document.querySelector("input[name=date1]"),
  date2 = document.querySelector("input[name=date2]"),
  button1 = document.querySelector("input[name=button1]");

button1.addEventListener("click", function() {
  var date1valid = date1.checkValidity();
  var date2valid = date2.checkValidity();
  if (date1valid && date2valid) {
    elapsedTime(date1.value, date2.value);
  } else {
    alert("Please provide both dates!");
  }
});

答案 1 :(得分:0)

您应该使用输入类型 def parse(self,response): return FormRequest.from_response(response, formxpath="//form[@class='btn-group']", clickdata={"value":"serp-grid"},callback = self.scrape_pages) 来使代码正常工作:

date