本文介绍了日期差异Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我们刚刚学习Js,我有一个问题,差异两个约会。我想计算当前日期和日历之间的差异。用户应在日历上选择日期。我的简单代码如下所示,我需要通过所有回复来改进它。

Hello guys I am just learning Js and I have a problem that differences two date. I want to calculate differences between current date and any date from calender. User should select date whatever you want on calender. My simple code following and I need to improve it thanks for all response.

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>

<script>

 var selectedDateFromCalendar = new Date();
 selectedDateFromCalendar = document.getElementById('mydate').value;

 var currentdate = new Date();
 currentdate = document.getElementById("current").value;

 var diff = selectedDateFromCalendar - currentdate  ;
 alert(diff);

</script>
</head>

<body>
<p id="current"></p>
<input type="date" id="myDate">

</body>
</html>


推荐答案

哪里有一些错误,我把它们都修好了:

There where quite some mistakes, I fixed them all here:

如果您无法理解其中的一部分,请随时发表评论。

If you can't understand some of this please feel free to leave a comment.

<!DOCTYPE html>
<html>

<head>
  <title>Page Title</title>
</head>

<body>
  <p id="current">2015-12-20</p>
  <input type="date" id="myDate" value="2015-12-25">


  <script>
    document.getElementById('myDate').onchange = function() {
      var selectedDateFromCalendar = this.value;

      var currentdate = new Date();
      document.getElementById("current").textContent = currentdate.toUTCString();

      var diff = new Date(selectedDateFromCalendar) - currentdate;
      var days = diff / 1000 / 60 / 60 / 24
      alert(days + " days"); // or use Math.floor(days)
    }
  </script>
</body>

</html>

这篇关于日期差异Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 00:56