【问题标题】:Converting HTML date from form into JavaScript to compare two dates. [duplicate]将 HTML 日期从表单转换为 JavaScript 以比较两个日期。 [复制]
【发布时间】:2015-04-29 12:17:03
【问题描述】:

我正在尝试编写一个使用 JavaScript 计算两个日期之间差异的程序。我要比较的两个日期是使用日期格式的 HTML 表单输入的。我想使用 javaScript 比较两个输入的日期,特别是找出两个日期在整周和剩余天数之间的差异。我已经设法比较了 javaScript 中的两个硬编码日期,但是在一个表单中使用两个日期时遇到了麻烦。任何指针将不胜感激! 下面是javaScript程序:

   <!DOCTYPE html>
   <html>
   <title> Dates </title>
   <head>Class Test

   <script language="javascript">
   function Ict5() { // ALERT BOX
   today = new Date(); //Using new Date(), creates a new date object with the current date and time

  birthday = new Date("March 28, 1995"); //using new date with stuff in the brackets, assigns the date to the variable
  birthday.setFullYear(1995); 
  msPerDay = 24 * 60 * 60 * 1000;
  msPerWeek = 7 * 24 * 60 * 60 * 1000;
  msBetween = (today.getTime() - birthday.getTime()); //get time Returns the number of milliseconds since midnight Jan 1, 1970
  daysBetween = Math.round(msBetween/msPerDay); //math round returns the value of a number rounded to the nearest integer.
  weeksBetween = Math.floor(msBetween/msPerWeek);
  window.alert("There are " +daysBetween+ " days or " +weeksBetween+ " full weeks between my date of birth and today ");
  }
  </script>
  </head>
  <body>

  <H1> An Example of Form </H1>



 <Form action="process.pl" method="POST" name="MyForm" onsubmit="return formValidation()">

            <p>Enter Date:</p>
            <input type=date name="date1" id="date1">
            <input type=date name="date2" id="date2">
 <button type="button" onclick="Ict5()">Calculate Fare</button><br>

    </Form>        


 </body>

</html> 

【问题讨论】:

标签: javascript html forms date


【解决方案1】:

您可以使用moment.js library 尤其是manipulation methods 来完成此操作。将 JS 日期转换为 moment 对象后,您可以查询 moment.week() 并获取您要查找的号码。

var week1 = moment("2015-2-1").week(); var week2 = moment("2015-2-8").week(); var numOfWeeksInBetween = week2 - week1;

【讨论】:

    【解决方案2】:

    您可以像这样从输入中获取值:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 2013-05-30
      • 2011-08-09
      • 1970-01-01
      相关资源
      最近更新 更多