A tutorial on how to define and present a date in a datetime-local HTML input element using JavaScript.

🌍 The French version of this publication : JavaScript : Comment définir et afficher une date dans un input datetime-local ?

An <input type="datetime-local"> is an HTML input type that allows the user to select both a local date and time in a web form.

In this tutorial, we'll look at how to define and present a value for this element using JavaScript.

First, we need to place the datetime-local input field on an HTML page.

<!-- The datetime-local entry -->
<label for="date_input">Enter date and time of activity</label>

<input type="datetime-local" name="date_input" id="date_input" >

In HTML, it's possible to specify the field value directly by supplying a date in date time string format in the value attribute. For example: "2024-01-27T15:50".

<input type="datetime-local" name="date_input" id="date_input" value="2024-01-27T15:50" >

In the same way, we can define this value in JavaScript by selecting the input element by its ID and assigning it a value via the value attribute :

document.getElementById("date_input").value = "2024-01-27T15:50"

We can also generate a custom date using the JavaScript Date object. Next, we can format this date using the toISOString() method, which follows the ISO format. Finally, to display it in the input element of type datetime-local, we extract the first 16 characters from the resulting string using the slice(0, 16) function.

// Customized date in year, month, day, hour and minute
var date = new Date(2027, 0, 27, 17, 35)

// Assign value to input
document.getElementById("date_input").value = date.toISOString().slice(0,16)

To conclude, here is the complete source code:

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS - Defining and displaying a date in a datetime-local input</title>
</head>
<body>

    <!-- The datetime-local entry -->
    <label for="date_input">Enter date and time of activity</label>

    <input type="datetime-local" name="date_input" id="date_input" >

    <script>

        // Customized date in year, month, day, hour and minute
        var date = new Date(2027, 0, 27, 17, 35)

        // Assign value to input
        document.getElementById("date_input").value = date.toISOString().slice(0,16)

    </script>
    
</body>
</html>

Take care! 😎