Convert HTML date from form to JavaScript to compare two dates.

I am trying to write a program that allows two dates to be separated using JavaScript. The two dates I want to compare are entered using an HTML form using a date format. I want to compare two entered dates using javaScript, in particular, to find the difference between the two dates in full weeks and then in the remaining days. I managed to compare two hardcoded dates in javaScript, but I was having problems with these two dates in the form. Any pointers would be much appreciated! The following is a javaScript program:

<!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> 
+5
source share
2 answers

You can accomplish this using library.js library , in particular, manipulation methods . After you click the JS date on the instant object, you can request moment.week() and get the number you are looking for.

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

+1
source

You can get the value from the inputs as follows:

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

Source: https://habr.com/ru/post/1214274/


All Articles