33

I would like to set the default date to be 3 days from todays date when the date picker opens up on the browser. How can I achieve that?

<input id="dateRequired" type="date" name="dateRequired" />

5 Answers 5

48

You need to convert the date to iso string and get first 10 characters. e.g.

var curr = new Date();
curr.setDate(curr.getDate() + 3);
var date = curr.toISOString().substring(0,10);
<input id="dateRequired" type="date" name="dateRequired" defaultValue={date} /> 

Reference toISOString method. Also you can see the result here

Sign up to request clarification or add additional context in comments.

Comments

20

You need set the defaultValue attribute of the date input as yyyy-mm-dd like so:

const today = new Date();
const numberOfDaysToAdd = 3;
const date = today.setDate(today.getDate() + numberOfDaysToAdd); 
const defaultValue = new Date(date).toISOString().split('T')[0] // yyyy-mm-dd

<input id="dateRequired" type="date" name="dateRequired" defaultValue={defaultValue} />

Here is a working example: https://codesandbox.io/s/gracious-christian-22czv?file=/src/App.js:326-346

2022 Answer

You can use toLocaleDateString with a locale to get the date string in yyyy-mm-dd format.

class App extends React.Component {

  render() {
    const date = new Date();
    const futureDate = date.getDate() + 3;
    date.setDate(futureDate);
    const defaultValue = date.toLocaleDateString('en-CA');

    return (
      <input id="dateRequired" type="date" name="dateRequired" defaultValue={defaultValue} />
    );
  }
}

ReactDOM.render(
  <App />,
  document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

5 Comments

Thank you for replying.. but the page does not render when i add defaultValue to the input field.
It says date is not defined.
Can you update your original post with your full component?
in my case was not working because i was passing a value as well: <input id="dateRequired" value ={date} type="date" name="dateRequired" defaultValue={date} />, removed value and it worked
This answer does not work!
4

2022 Answer

using jsx

import { useState } from 'react'

const Component = () => {
    
    let defaultDate = new Date()
    defaultDate.setDate(defaultDate.getDate() + 3)

    const [date, setDate] = useState(defaultDate)

    const onSetDate = (event) => {
        setDate(new Date(event.target.value))
    }

    return (
        <>
            <p>date: {date.toString()}</p>
            <p>date: {date.toLocaleDateString('en-CA')}</p>
            <input type="date" value={date.toLocaleDateString('en-CA')} onChange={onSetDate} />
        </>
    )
}

export default Component

using tsx

import { useState } from "react"

const Component = (): JSX.Element => {
    
    let defaultDate = new Date()
    defaultDate.setDate(defaultDate.getDate() + 3)

    const [date, setDate] = useState<Date>(defaultDate)

    const onSetDate = (event: React.ChangeEvent<HTMLInputElement>): void => {
        setDate(new Date(event.target.value))
    }

    return (
        <>
            <p>date: {date.toString()}</p>
            <p>date: {date.toLocaleDateString('en-CA')}</p>
            <input type="date" value={date.toLocaleDateString('en-CA')} onChange={onSetDate} />
        </>
    )
}

export default Component

1 Comment

This code breaks if someone tries to type in the date because invariably the date is temporarily in invalid date states and the call to toLocalDateString() fails...
3

Create a helper function that returns the correct format of the <input type="date" /> which is yyyy-mm-dd.

Let's define a function:

const getCurrentDateInput = () => {

  const dateObj = new Date();

  // get the month in this format of 04, the same for months
  const month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
  const day = ("0" + dateObj.getDate()).slice(-2);
  const year = dateObj.getFullYear();

  const shortDate = `${year}-${month}-${day}`;

  return shortDate;
};

Then go back to the input tag and type the following :

<input type="date" defaultValue={getCurrentDateInput()}  />

2 Comments

should I do this in useEffect or just a regular JS function?
no, you just put in a regular function or separate file, and call it whenever u need it.
2

Declare a state :-

this.state={ 
   recentDate:new Date().toISOString().slice(0,10)
}

Declare a function by means of which you can also be able select different dates.

selectedDate(e){    
     this.setState({recentDate:e.target.value})    
}

Call the state into value attribute and selectedDate function in onChange prop.

<input 
    type="date" 
    value={this.state.rencentDate} 
    onChange={this.selectedDate} 
 />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.