'How to get hour from datetime-local?

I'm trying to get the hour in different ways from a datetime-local input but every time I've got the output as "invalid" date.

So I would like to know how can I get the hour from a datetime-local input using jquery or js.

Here is what I've tried:

var fine =  moment($('#datafine').val).format("HH");

And without moment that was something like

var datafine = new Date($('#datafine').val);


Solution 1:[1]

When you get the value from the input, it is converted to a standard format, regardless of the displayed format:

One thing to note is that the displayed date and time formats differ from the actual value; the displayed date and time are formatted according to the user's locale as reported by their operating system, whereas the date/time value is always formatted yyyy-MM-ddThh:mm.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local

So you can use this with new Date(val).getHours() to get the hours.

Using jQuery:

var hour = new Date($('input[type="datetime-local"]').val()).getHours()
console.log($('input[type="datetime-local"]').val(), hour)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="party">Enter a date and time for your party booking:</label>
<input id="party" type="datetime-local" name="partydate" value="2019-06-01T19:30">

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours

Solution 2:[2]

If I understand correctly what you're trying to do, something like this may help. You would just need to add in the date value from your input into new Date(). The code below would give you the hours in the specified locale.

const date = new Date();
const options = { hour12: false, hour: 'numeric'};
const hours = date.toLocaleTimeString('en-US', options); 

console.log(hours)

Date.prototype.toLocaleTimeString() on MDN

Solution 3:[3]

This worked for me:

new Date($('input[type="datetime-local"]').val()).toLocalTimeString()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 freedomn-m
Solution 2 Maciej S.
Solution 3 Matt