【问题标题】:How to pass only the date to the database (without passing the time) using react-datetime picker如何使用 react-datetime 选择器仅将日期传递给数据库(不传递时间)
【发布时间】:2021-09-26 00:31:04
【问题描述】:

如何使用 react-datetime 选择器仅将日期传递给数据库(不传递时间)。

目前在我的代码中,它将像这样 (2021-09-07T18:30:00.000Z) 将日期和时间传递给后端。

我只想传递像 (2021-09-07) 这样的日期而不传递时间。 使用 react-datetime 选择器

请帮帮我!

                         <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}
                          /> 

【问题讨论】:

  • 不了解 formik,但通常你应该能够使用 vanilla js 和 momenjs 之类的库仅获取日期部分。仅从该“值”参数中获取日期部分。
  • 如果需要,将value 转换或转换为字符串dateStr,然后执行dateStr.split("T")[0] 之类的操作?

标签: reactjs react-datetime


【解决方案1】:

您可以使用以下语句将日期作为具有该格式的字符串获取

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

如果您需要交换日期和月份,请使用'en-US'

如果您想要任何自定义格式,请一一获取并附加如下

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

【讨论】:

    【解决方案2】:

    在handleChange方法中,你可以像这样格式化日期。

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

    如果你使用像momentjs这样的库,你可以像这样简单地格式化日期

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-20
      • 2017-10-08
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      相关资源
      最近更新 更多