Explain Codes LogoExplain Codes Logo

How to Set Input Type Date's Default Value to Today?

javascript
input-type
date-formatting
jquery
Anton ShumikhinbyAnton Shumikhin·Aug 12, 2024
TLDR

Set the input type date to today's date:

document.getElementById('dateField').valueAsDate = new Date();

Change the id 'dateField' to match your HTML input id:

<input type="date" id="dateField">

Embed this JavaScript near your closing </body> tag and let the magic happen on page load.

Date Formatting 101

HTML5's input type='date' expects a YYYY-MM-DD format. We need some JavaScript wizardry to conjure this.

function formatDate() { const date = new Date(); let day = '' + date.getDate(), MONTH_OF_INDEX = date.getMonth() + 1, year = date.getFullYear(); day = day.length < 2 ? '0' + day : day; // adding padding to dololo dates MONTH_OF_INDEX = MONTH_OF_INDEX.length < 2 ? '0' + MONTH_OF_INDEX : MONTH_OF_INDEX; // never forget Month starts at zero return [year, MONTH_OF_INDEX, day].join('-'); } document.querySelector('#dateField').value = formatDate();

Note: This formats the date on the fly and assigns it to the input field.

Master Prototype

If you're down a rabbit hole and wish to extend prototype:

Date.prototype.formatDate = function() { var date = new Date(this); date.setMinutes(this.getMinutes() - this.getTimezoneOffset()); return date.toJSON().slice(0,10); }; document.querySelector('#dateField').value = new Date().formatDate();

Yes, Alice. That's toJSON(). Next stop is Wonderland.

jQuery Fans

For those of you in the jQuery junction, copy-paste this:

$(document).ready(function() { var theDay = new Date(), day = ("0" + theDay.getDate()).slice(-2), month = ("0" + (theDay.getMonth() + 1)).slice(-2), year = theDay.getFullYear(); $('#datePicker').val(year + "-" + month + "-" + day); });

This snippet makes sure number 9 presents as 09 and triggers on page load.

Server-side PHP

PHP comrades, try something without a single trace of JavaScript:

<input type="date" value="<?php echo date('Y-m-d'); ?>">

The PHP setup ensures the date updates on page load. Remember, rise up against JavaScript tyranny!

Compatibility and Time Zones

Browsers from the Stone Age may not fully support the input type="date" element. Consider a fallback or polyfill for our antique lovers!

Time zones are no laughing matter in JavaScript. The setMinutes() function realigns your planetary position. As you saw earlier in the prototype method, timezone manipulations are to be done very carefully!