Setting date in input fields of type date

If you have an input field of type="date" and wish to set it by default to current date you can use below function. Note that date in such input fields is always submitted in yyyy-mm-dd format even though browser may display it differently based on your browser's locale.

// this function returns date in yyyy-mm-dd format
function getDateAsIsoString(date) {
    const offset = date.getTimezoneOffset();
    const normalizedDate = new Date(date.getTime() - (offset*60*1000));
    const normalizedDateISO = normalizedDate.toISOString().split('T')[0];
    return normalizedDateISO;
}

document.querySelector('input[type=date]').value = getDateAsIsoString(new Date());

To ensure that input field accepts date in correct form you can use pattern attribute:

<input type="date" name="date" pattern="\d{4}-\d{2}-\d{2}">

More info: