Table of Contents

How to create a date field in an HTML form? (at the month, day, hour and minute level)

About

This article shows you how to create a form control for date element at the:

The control are all input control with different type value.

Type

Year / Month / Day

On a Year/Month/Day level, you use the date type. 1)

Example in Pure HTML

<input type="date"  placeholder="date input" />

You may also want to use a library:

Year/Month/Day Hour:Minute (DateTime)

When you want to add a time component to your day, you use the datetime-local type 2)

It's the native HTML5 control for entering a date and time, without any time zone information.

Example:

<form>
   <input type="datetime-local"  value="0170-07-31T22:00:00" name="mydate" />
   <button type="submit">Submit</button>
</form>
// set the value with Javascript
const now = new Date(); 
const nowString = now.toISOString().substring(0,16); // toISOString returns UTC
document.querySelector('input[type="datetime-local"]').value = nowString;
document.querySelector('form').addEventListener("submit", (event)=>{
  // to not execute the default form action and goes away
  event.preventDefault();
  console.log(event.target.mydate.value);
});

Time

en-US/docs/Web/HTML/Element/input/time

<input type="time"  placeholder="time input" />

Month

en-US/docs/Web/HTML/Element/input/month

<input type="month"  placeholder="month input" />