'DatePicker date input with custom format

I want to stote dates in my state using redux-form. I use react-datepicker. To make the datepicker compatible with my redux-form i write:

import React, { PropTypes } from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';

    const MyDatePicker = ({ input, meta: { touched, error } }) => (
      <div>
        <DatePicker
          {...input} dateFormat="YYYY-MM-DD"
          selected={input.value ? moment(input.value) : null}
        />
        {
          touched && error &&
          <span className="error">
            {error}
          </span>
        }
      </div>
    );

    MyDatePicker.propTypes = {
      input: PropTypes.shape().isRequired,
      meta: PropTypes.shape().isRequired
    };

    export default MyDatePicker;

The problem is that when i choose date i want it to show as DD-MM-YYYY but i want the date to be saved in my state with the YYYY-MM-DD HH:MM:SS format. How to do this? I use the moment's format function but it did not seem to work



Solution 1:[1]

If i am understanding correct you just need 2 different formats for same date one on UI and other to save ? moment(date).format('DD-MM-YYYY') and moment(date).format('YYYY-MM-DD HH:MM:SS') will give you both formats date.

Solution 2:[2]

Just use the prop dateFormat="dd/MM/yyyy"

Example :

<DatePicker 
    selected={startDate} 
    onChange={date => handleChange(date)} 
    dateFormat="DD/MM/YYYY"
/>

Solution 3:[3]

I used the below props -mask, inputFormat and format - to change the default format to "yyyy-MM-dd" format. The format code "yyyy-MM-dd" is important, play around this to find the desired format.

Example:

<LocalizationProvider dateAdapter={AdapterDateFns} >
   <DatePicker
      label="SomeDate"
      {...register("details_received_date")}
      mask="____-__-__"
      inputFormat="yyyy-MM-dd"
      format="yyyy-MM-dd"
      value={someDate}
      onChange={(newValue) => {setSomeDate(newValue);}}
      renderInput={(params) => <TextField {...params} />}
      />
</LocalizationProvider>

This will display in the front end and provide the value as well in the desired format. Hope this helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MGA
Solution 2 Kuldeep Sharma
Solution 3 Tutoo Joe Philip