1

I have this html:

<input required="" id="time" type="time">

js:

var time = $('#time').val();
console.log(time); // it outputs e.g. 10:00
var newTime = time--; // NaN
var convert = new Date(time); // Invalid Date

How to work with the value of input? I want to compare it to the other input's value or other basic operations like decrease time with 1 hour but I'm not able to convert it to Date object.

6
  • It's just a string w3schools.com/jsref/prop_input_time_value.asp Commented Nov 7, 2015 at 16:48
  • document.querySelector("#time").valueAsDate or .valueAsNumber -> HTMLInputElement Commented Nov 7, 2015 at 16:49
  • I know, but question is how to convert it to date? edit: thanks Commented Nov 7, 2015 at 16:49
  • is there any way how to get that value in jquery(with $(this))? $(this).valueAsDate doesn't work Commented Nov 7, 2015 at 16:57
  • @dontHaveName "is there any way how to get that value in jquery(with $(this))? $(this).valueAsDate doesn't work" valueAsDate is DOM element proerty , not jQuery method . See post. Commented Nov 7, 2015 at 16:58

1 Answer 1

2

Try using valueAsDate property

$("input[type=time]").on("change", function() {
  console.log(this.valueAsDate)
})
<input required="" id="time" type="time">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

2 Comments

and any way how to get it back to hh:mm? just with new Date(value) right?
@dontHaveName "any way how to get it back to hh:mm?" Try this.valueAsDate.toJSON().slice(-13, -8) . Could also use this.valueAsDate.getHours() , this.valueAsDate.getMinutes()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.