Home > Mobile >  How to set a default value for input type date
How to set a default value for input type date

Time:12-06

I would like to set the default date to the last day of the month when the date picker opens on the browser. How can I achieve this?

CodePudding user response:

This should do:

const now = new Date();
const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth()   1, 0);
const defaultDate = lastDayOfMonth.toISOString().substring(0, 10);

return (
  <div className="App">
    <input
      type="date"
      defaultValue={defaultDate}
    />
  </div>
);

CodePudding user response:

I suggest you use the moment library. It's much easier to do any date related thing with that: https://momentjs.com/

<DatePicker
  selected={moment().endOf('month').format('YYYY-MM-DD')}
/>
  • Related