generate a web form that allows you to input two dates and get the number of days between the two dates in javascript

<!--HTML-->
<form>
  <label for="date1">First Date:</label>
  <input type="date" id="date1">
  
  <label for="date2">Second Date:</label>
  <input type="date" id="date2">
  
  <button type="button" onclick="calculateDays()">Calculate Days</button>
</form>

<p id="result"></p>
277 chars
13 lines
/*CSS - only for styling*/

label {
  margin-right: 5px;
}

button {
  margin-top: 10px;
}

#result {
  margin-top: 20px;
  font-weight: bold;
}
145 chars
15 lines
index.tsx
//JavaScript

function calculateDays() {
  const date1 = new Date(document.getElementById("date1").value); //get first date
  const date2 = new Date(document.getElementById("date2").value); //get second date

  const oneDay = 24 * 60 * 60 * 1000; //calculate number of milliseconds in one day
  const diffDays = Math.round(Math.abs((date2 - date1) / oneDay)); //calculate difference in days
  
  document.getElementById("result").innerHTML = `Number of days between the two dates: ${diffDays}`; //display result
}
514 chars
12 lines

This code creates a simple HTML form with two date inputs and a button to calculate the difference in days between the two dates using javascript. When the button is clicked, the calculateDays() function is called, which first gets the two dates from the input fields, converts them to date objects, and then calculates the difference in days using simple math. Finally, the result is displayed on the page.

related categories

gistlibby LogSnag