Cory Rylan

My name is . Google Developer Expert, speaker, and Software Developer at VMware Clarity Design System.

Follow @coryrylan
JavaScript

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!

View Demo Code   
 

No spam. Short occasional updates on Web Development articles, videos, and new courses in your inbox.

Related Posts

Web Performance

Design System Performance with Clarity Core Web Components

Learn how to build high performance UI and Design Systems on the Web using Clarity Core.

Read Article
Web Components

State of Web Components in 2020

Learn a brief overview on Web Components and the latest tech available to build and distribute components across the Web.

Read Article
JavaScript

Wrapping DOM Text Nodes with JavaScript

Sometimes, due to CSS constraints, we need to find DOM text nodes and wrap them with a span or div. This post, we will see how to preserve any existing references safely.

Read Article