Hi I’m a newbie in JavaScript and have little to no experience in it. Clicking the button will print the input time.
What i was trying to do was subtract the time by 9 hours 30 minutes and I’m unable to find a way to do it.
It will help me a lot if someone could explain how to do this.
I’ve attached the whole HTML document below.
JavaScript
x
4
1
function myFunction() {
2
var x = document.getElementById("meeting-time").value;
3
document.getElementById("demo").innerHTML = x;
4
}
JavaScript
1
3
1
<input type="datetime-local" id="meeting-time" name="meeting-time">
2
<button onclick="myFunction()">click to print time</button>
3
<p id="demo"></p>
Advertisement
Answer
You have to make use of the Date Object.
- Pass the input as a Date object
- Set the new date by subtracting hours and minutes as necessary
Side Note: If you have more complex operations which include dates, you can make use of a third-party library like Moments Js
JavaScript
1
7
1
function myFunction() {
2
var x = document.getElementById("meeting-time").value;
3
var date = new Date(x); // parse date as a Date object: TODO: Error handling -> sanitize the input
4
date.setHours(date.getHours() - 9); // change the date object by subtracting hours from the same date object
5
date.setMinutes(date.getMinutes() - 30); // change the date object by subtracting minutes from the same date object
6
document.getElementById("demo").innerHTML = date;
7
}
JavaScript
1
3
1
<input type="datetime-local" id="meeting-time" name="meeting-time">
2
<button onclick="myFunction()">click to print time</button>
3
<p id="demo"></p>