How to set input type date's default value to today?

后端 未结 30 3478
刺人心
刺人心 2020-11-22 14:00

The HTML5 input types are great, Opera\'s new built-in date picker is a breeze, and Chrome has at least supported the new input type with a spin-wheel implementation.

<
30条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 14:33

    Both top answers are incorrect.

    A short one-liner that uses pure JavaScript, accounts for the local timezone and requires no extra functions to be defined:

    const element = document.getElementById('date-input');
    element.valueAsNumber = Date.now()-(new Date()).getTimezoneOffset()*60000;

    This gets the current datetime in milliseconds (since epoch) and applies the timezone offset in milliseconds (minutes * 60k minutes per millisecond).

    You can set the date using element.valueAsDate but then you have an extra call to the Date() constructor.

提交回复
热议问题