Tag Archives: javascript

Prefilling a Date Input with the Local Date

I’m working on an app that has a date picker and I’d like to prefill it with the current date.

I found Prefilling a Date Input on CSS Tricks, but that code returns a UTC date instead of the local date. After stumbling around for a while, I figured out a solution with JavaScript:

let $localDate = new Date().toLocaleDateString();
$localDate = new Date($localDate);
document.querySelector("#local-date").valueAsDate = $localDate;

toLocaleDateString() converts the date to the local date and then the second line creates a new Date object based on that local date. Without creating the new Date object, I was getting this error:

TypeError: HTMLInputElement.valueAsDate setter: Value being assigned is not an object.

For the record, the date input in my form looks like this:

<input type="date" name="date" id="local-date" required>