About
This article shows you how to create a form control for date element at the:
- day
- second
- minute
- and month level
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:
- https://getdatepicker.com/ - Tempus Dominus (works with floating ui)
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:
- The HTML
<form>
<input type="datetime-local" value="0170-07-31T22:00:00" name="mydate" />
<button type="submit">Submit</button>
</form>
- How to set it up with the local date time
// 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;
- How to transform it to UTC after a submit
document.querySelector('form').addEventListener("submit", (event)=>{
// to not execute the default form action and goes away
event.preventDefault();
console.log(event.target.mydate.value);
});
- Result:
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" />