0

I am using material-ui/DatePicker I am getting date in full format I need only the DD-MM-YYYY

import DatePicker from 'material-ui/DatePicker';

datepicker Component

<DatePicker
   hintText=""
   formatDate={(date) => moment(date).format('DD-MM-YYYY')}
   value={this.state.contractDate}
   onChange={this.handleContractDateChange}
  />

On change Function looks like below

handleContractDateChange = (event, date) => {
    this.setState({
              contractDate: date,
            });

          }
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
user9883888
  • 389
  • 1
  • 8
  • 17
  • Possible duplicate of [How to get current formatted date dd/mm/yyyy in Javascript and append it to an input](https://stackoverflow.com/questions/12409299/how-to-get-current-formatted-date-dd-mm-yyyy-in-javascript-and-append-it-to-an-i) – kayakpim Jun 22 '18 at 09:21
  • https://codesandbox.io/s/ojp0kkz619 – AmitJS94 Jun 22 '18 at 09:24

3 Answers3

2

There is a method to convert JS Date Object to DD-MM-YYYY which is as follows

function formatDate(oDate) {
    var oTempDate = new Date(oDate),
        sMonth = '' + (oTempDate.getMonth() + 1),
        sDay = '' + oTempDate.getDate(),
        iYear = oTempDate.getFullYear();

        if (sMonth.length < 2) { sMonth = '0' + sMonth; }
        if (sDay.length < 2) { sDay = '0' + sDay; }

        return [sDay, sMonth, iYear].join('-');
}
Darshna Rekha
  • 1,069
  • 7
  • 20
0

Do it like below using pure JavaScript:

let date = new Date("Fri Jun 22 2018 14:37:47 GMT+0530 (India Standard Time)");

let dd = date.getDate();
let mm = date.getMonth() + 1;
let yyyy = date.getFullYear();

console.log(dd + "-" + mm + "-" + yyyy);
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
0

From what I see in the documentation (https://v0.material-ui.com/#/components/date-picker) the prop formatDate is just for formatting the value of the date picker that is displayed in the field after picking a date. Your onChange handler still gets called with the date object. You have to call moment.format() again in your onChange handler.

handleContractDateChange = (event, date) => {
  const formattedDate = moment(date).format('DD-MM-YYYY');
  // Use formattedDate

  this.setState({
    contractDate: date,
  });
}
Shriharsha KL
  • 317
  • 1
  • 2
  • 11