Search code examples
javascriptreactjsreact-datepicker

How can I get rid of all the extra numbers in this return date from react-date-picker?


I am trying to just show the Month and Day but I am getting "Tue Oct 22 2019 00:00:00 GMT-0700 (Mountain Standard Time)". When using "react-date-picker", how can I just have it return ex: "Tue Oct 22 2019" without resorting to truncating the text?

<DatePicker
  name="date"
  onChange={this.handleDate}
  value={this.state.date}
  format="M-dd"
/>

Solution

  • This is what you're looking for - toLocaleDateString()

    const today = new Date();
    
    console.log(today); // "2019-10-17T04:38:49.459Z"
    
    console.log(today.toLocaleDateString("en-US")); // 10/17/2019

    ` - Returns the second (0-59).

    Additionally, JavaScript Date has several methods allowing you to extract its parts:

    getFullYear() - Returns the 4-digit year
    getMonth() - Returns a zero-based integer (0-11) representing the month of the year.
    getDate() - Returns the day of the month (1-31).
    getDay() - Returns the day of the week (0-6). 0 is Sunday, 6 is Saturday.
    getHours() - Returns the hour of the day (0-23).
    getMinutes() - Returns the minute (0-59).`

    There are a few more, but these are the important ones.

    May I also suggest exploring the moment.js library.