Use JavaScript Date Objects with the HTML5 Date Picker
Cory Rylan
- 1 minute
Sometimes when building out a form on the Web, we need something simple and light. There is nothing more lightweight when it comes to date pickers than the native HTML5 date picker input. While most HTML input values are string-based, the HTML5 date picker has a helpful JavaScript Date value API. This makes working with the native date picker much easier. Let's take a look at using the native date picker with both string and date values.
HTML Date Picker with Strings
First, let's create a date picker input and use a string date to get and set the value.
<label for="date-string">Date String</label>
<input type="date" id="date-string" />
const input = document.querySelector('#date-string');
input.value = '2021-03-31';
input.addEventListener('input', () => {
console.log(input.value) // 2021-03-31
});
When setting the native date picker using string values, the value must follow the following format, YYYY-MM-DD
. When getting the value after an input event, we will get back the same string format.
This works ok, but often we need to convert to and from our string to a JavaScript Date object. Instead of having to write conversion logic, we can use the valueAsDate
API.
HTML Date Picker with Dates
The valueAsDate
allows you to set and get the date picker value as a JavaScript Date object rather than the default value string. Let's take a look at an example.
<label for="date-object">Date Object</label>
<input type="date" id="date-object" />
const input = document.querySelector('#date-object');
input.valueAsDate = new Date('2021-03-31'); // set using Date objects
input.addEventListener('input', () => {
console.log(input.valueAsDate); // Tue Mar 16 2021 19:00:00 GMT-0500 (Central Daylight Time)
});
With the valueAsDate
API working with a native date picker is more straightforward and provides a simple, lightweight date picker when we need it. Check out the demo below!