I'm trying to calculate the number of months between two HTML date time inputs.
This means the expected result is when the user selects 7/21/21 from the dropdown calendar as a start date and 8/21/21 as an end date then it would be one month.
My actual results are not displayed on the screen.
I didn't get any error messages so I don't know what to fix.
I tried calculating the month difference between two dates by using Date.parse().value
on the start date (movein-input
) and the end date (moveout-input
) and calculating the time apart in milliseconds(ms), minute, hour, day, month, year, years, months, days, and hours but it did work. I found the idea on youtube (https://www.youtube.com/watch?v=Q3oiSwdGAq8) and w3schools (https://www.w3schools.com/jsref/jsref_parse.asp).
W3schools said when you display a date object in HTML, it is automatically converted to a string so I thought I could use the html date input in Date.Parse().value
.
This is my JavaScript code
function calculatePrice() {
let d1 = document.getElementById("movein-input").value;
let d2 = document.getElementById("moveout-input").value;
let msBetweenD1And1970 = Date.parse(d1);
let msBetweenD2And1970 = Date.parse(d2);
let timeInMs = msBetweenD2And1970-msBetweenD1And1970;
let ms = timeInMs;
let second = 1000;
let minute = second*60;
let hour = minute*60;
let day = hour*24;
let month = day*30;
let year = day*365;
let years = Math.round(ms/year);
let months = years*12;
var t1 = "That is : "+months;
document.getElementById("m").innerHTML=t1
}
I also have the html code
<h2><span id="m">$</span></h2>
Calculate price is in the button
<button onclick="calculatePrice()">Enter</button>