Home > Software design >  How to pass only the date to the database (without passing the time) using react-datetime picker
How to pass only the date to the database (without passing the time) using react-datetime picker

Time:09-26

How to pass only the date to the database (without passing the time) using react-datetime picker.

Currently in my code it will pass both date and time to the backend like this (2021-09-07T18:30:00.000Z).

I want to pass only the date like (2021-09-07) without the time. using react-datetime picker

please help me!

                         <ReactDatetime
                            inputProps={{
                              placeholder: "MM/DD/YY",
                            }}
                            dateFormat="DD/MM/YYYY"
                            timeFormat={false}
                            onChange={(value) =>
                              formik.handleChange({
                                target: {
                                  name: "date_of_the_event",
                                  value,
                                },
                              })
                            }
                            onBlur={formik.handleBlur}
                            value={formik.values.date_of_the_event}
                          /> 

CodePudding user response:

you can get your date as a string with that format by using the below statement

   const formattedDate =  date.toLocaleString('en-GB', { day: 'numeric', month: 'numeric', year: 'numeric' })

If you need to swap date and month use 'en-US'

If you want any custom format get one by one and append it like below

 const formattedDate = 
 `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`

CodePudding user response:

In the handleChange method, you can format the date like this.

const formattedDate = `${date.getFullYear()}-${date.getMonth() 1}-${date.getDate()}`

If you use a library like momentjs, you can simply format the date like this

const formattedDate = moment(date).format('YYYY/MM/DD');

  • Related