Skip to content
Advertisement

How to convert html5 input type date and time to javascript datetime

I’m working with html5 input types: date and time. How to convert the form input type to javascript object Date (that includes time in it)?

Here is a part of my code:

<html>
    <head>
        <script type="text/javascript">
             function getDate(date, time)
             {
                  var theDate = new Date();
                  ....
             }
        </script>
    </head>
    <body>
        <form name="form_task">
             Date:<input type="date" name="task_date" />
             Time:<input type="time" name="task_time" />
             <input type="button" onclick="getDate(task_date.value, task_time.value)" />
        </form>
    </body>
</html>

Advertisement

Answer

All you need to do is pull the value from both inputs, concatenate them, then pass them to a date object.

Fiddle: http://jsfiddle.net/P4bva/

HTML

Date:<input id="date" type="date" name="task_date" />
Time:<input id="time" type="time" name="task_time" />
<button id="calc">Get Time</button>

JS

var calc = document.getElementById("calc")

calc.addEventListener("click", function() {
    var date = document.getElementById("date").value,
        time = document.getElementById("time").value

    console.log(new Date(date + " " + time))
})
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement