Skip to content
Advertisement

How do i subtract time from a datetime-local input?

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.

function myFunction() {
  var x = document.getElementById("meeting-time").value;
  document.getElementById("demo").innerHTML = x;
}
<input type="datetime-local" id="meeting-time" name="meeting-time">
<button onclick="myFunction()">click to print time</button>
<p id="demo"></p>

Advertisement

Answer

You have to make use of the Date Object.

  1. Pass the input as a Date object
  2. 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

function myFunction() {
  var x = document.getElementById("meeting-time").value;
  var date = new Date(x); // parse date as a Date object: TODO: Error handling -> sanitize the input
  date.setHours(date.getHours() - 9); // change the date object by subtracting hours from the same date object
  date.setMinutes(date.getMinutes() - 30); // change the date object by subtracting minutes from the same date object
  document.getElementById("demo").innerHTML = date;
}
<input type="datetime-local" id="meeting-time" name="meeting-time">
<button onclick="myFunction()">click to print time</button>
<p id="demo"></p>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement