【问题标题】:ant design - datepicker with time saves with 00:00:00 as time?ant design - 带时间的日期选择器将 00:00:00 保存为时间?
【发布时间】:2021-11-03 14:04:18
【问题描述】:

所以我在 React 前端使用 antd 进行设计。我想在数据库中存储一个带有日期时间的对象。我看到 antd 的 Datepicker 能够做到这一点,但它总是以 00:00:00 作为时间存储在我的数据库中。日期、月份年份都可以。

我尝试使用moment().format('YYYY-MM-DD HH:mm:ss') 并将其保存在数据库中,但我收到错误Uncaught TypeError: date.clone is not a function

这是我的日期选择器。当我尝试从 useState 使用我的 setPickedFrom 函数时,问题就出现了。为什么会出现这个问题?

<DatePicker
                allowClear={false}
                placeholder="Rent from: "
                // format="YYYY-MM-DD HH:mm:ss"
                disabledDate={disabledDate}
                onChange={(e) => onDateClear(e, "from")}
                onOk={(date) =>
                  setPickedFrom(
                    moment(date).format("YYYY-MM-DD HH:mm:ss"),
                    "to"
                  )
                }
                value={pickedFrom ? pickedFrom : null}
                showTime
                className="date-picker2"
              />

保存日期功能(创建租金)

  const createRent = () => {
    axios
      .post("http://localhost:5000/rents/createRent", {
        date_from: pickedFrom,
        date_to: pickedUntil,
        userId: user.id,
        itemId: currentItem.id,
      })
      .then(() => {
        showNotification("Item rented");
        setCurrentItem({});
        setDifference(null);
        setIsModalVisible(false);
        setPickedFrom(null);
        setPickedUntil(null);
      })
      .catch((e) => {
        showNotification(e.response.data.message, "error");
      });
  };

我只需要找到一种方法以以下格式 (YYYY-MM-DD HH:mm:ss) 在我的数据库中保存日期和时间,因为这是我的数据库可接受的格式。

【问题讨论】:

    标签: reactjs date datetime antd


    【解决方案1】:

    这就是你要找的东西

    const onOk = (value) => {
        console.log("onOk: ", moment().format());
        console.log("onOk: ", typeof value);
        console.log("onOk: ", value.format("YYYY-MM-DD HH:mm:ss"));
      };
    <DatePicker format="YYYY-MM-DD HH:mm:ss" showTime={true} onOk={onOK}/>
    

    【讨论】:

    • 嗯...但这如何帮助我在数据库中保存正确的格式?这只是在控制台中打印出来?
    • @MarkoMarchisio 你可以做任何“价值”的事情
    • 它仍然没有时间保存在我的数据库中。例如,我希望它保存为 2021-11-05 09:07:32,而不是保存为 2021-11-05 00:00:00 。所以,问题是,在我的状态设置“值”的过程中,moment() 的时间部分丢失了。我尝试使用 moment().format() 将其保存为格式化 ('YYYY-MM-DD HH:mm:ss") 但我收到错误 TypeError: date.clone is not a function
    • @MarkoMarchisio 请分享您用来节省数据库时间的功能
    • 我编辑了帖子,添加了功能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 2021-03-25
    • 1970-01-01
    相关资源
    最近更新 更多