JavaScript:从带有时间的字符串创建日期对象

huangapple go评论67阅读模式
英文:

Javascript: Create Date object from a string with a time

问题

项目设置

  • 后端使用 Django 和 Django REST Framework
  • 前端使用 React 和 AntD

问题

我的后端有一个 DateFieldTimeField 字段,返回格式为 "YYYY-MM-DD" 和 "HH:mm:ss" 的字符串。我尝试让 AntD 接受这些值作为初始值,但问题是 AntD 似乎期望一个 Date 对象,因为每当我尝试传递这些字符串本身时,我会得到一个 date.format is not a function 错误。我猜想 AntD 正试图格式化日期,但它们实际上是字符串。

代码

以下是我提出问题的最小示例。如果使用以下依赖项运行此示例,它会产生 date.clone is not a function 错误。

import { Form, DatePicker, TimePicker, Input } from "antd";

const initial_data = {
  title: "Title",
  date: "2023-12-05",
  time: "10:23:00"
}

export function Playground() {
  return (
    <Form initialValues={initial_data}>
      <Form.Item name="title">
        <Input placeholder="Title" />
      </Form.Item>
      <Form.Item name="date">
        <DatePicker format="DD/MM/YYYY" placeholder="选择日期" />
      </Form.Item>
      <Form.Item name="time">
        <TimePicker format="HH:mm" placeholder="选择时间" />
      </Form.Item>
    </Form>
  );
}

依赖项:

  • react: 18.2.0
  • react-dom: 18.2.0
  • antd: 4.24.8

我尝试过的事情

对于 DateField,我没有问题,我只需使用 moment 创建一个 Date 对象即可。但是,我尚未找到如何将时间字符串 "HH:mm:ss" 转换为 Date 对象,以便 AntD 可以正确使用它。

是否有办法做到这一点,或者对于解决这个问题有其他想法?

英文:

Project setup

  • Django and Django REST Framework on the backend
  • React and AntD on the frontend

Problem

I have a DateField and TimeField fields in my backend that return a string with format "YYYY-MM-DD" and "HH:mm:ss" respectively. I'm trying to get AntD to accept these values as an initial value, but the problem is that it seems that AntD expects a Date object, because anytime I try to pass the strings themselves I get an date.format is not a function error. I guess that AntD is trying to format the dates, but they're actually strings.

Code

Next is a minimal example of the problem I'm presenting. If running this with the following dependencies, it produces the error date.clone is not a function.

import { Form, DatePicker, TimePicker, Input } from &quot;antd&quot;;

const initial_data = {
  title: &quot;Title&quot;,
  date: &quot;2023-12-05&quot;,
  time: &quot;10:23:00&quot;
}

export function Playground() {
  return (
    &lt;Form initialValues={initial_data} &gt;
      &lt;Form.Item name=&quot;title&quot; &gt;
        &lt;Input placeholder=&quot;Title&quot; /&gt;
      &lt;/Form.Item&gt;
      &lt;Form.Item name=&quot;date&quot; &gt;
        &lt;DatePicker format={&quot;DD/MM/YYYY&quot;} placeholder=&quot;Pick a date&quot; /&gt;
      &lt;/Form.Item&gt;
      &lt;Form.Item name=&quot;time&quot; &gt;
        &lt;TimePicker format={&quot;HH:mm&quot;} placeholder=&quot;Pick a date&quot; /&gt;
      &lt;/Form.Item&gt;
    &lt;/Form&gt;
  );
}

Dependencies:

  • react: 18.2.0
  • react-dom: 18.2.0
  • antd: 4.24.8

Things I've tried

For the DateField I have no problem, simply I use moment to create a Date from it. However, I haven't found how to transform the time string "HH:mm:ss" into a Date object so that AntD can properly work with it.

Is there a way to do this, or any other idea on how I should work around this issue?

答案1

得分: 1

Antd Datepicker和Timepicker接受类型为moment的值(Antd v5使用dayjs而不是moment)。对于Timepicker,你需要在moment的第二个参数中指定格式,如 moment('10:23:00', 'HH:mm')

由于你从后端接收所有值,并且为了在表单中设置这些值,你需要使用useForm钩子。

以下是格式化并在表单中设置值的完整代码:

import moment from "moment";
import { useEffect } from "react";
import { Form, DatePicker, TimePicker, Input } from "antd";

export function Playground() {
  const [form] = Form.useForm();

  useEffect(() => {
    // 从后端获取数据....
    const response = {
      title: "Title",
      date: "2023-12-05",
      time: "10:23:00",
    };

    form.setFieldsValue({
      ...response,
      date: moment(response.date),
      time: moment(response.time, "HH:mm"),
    });
  }, [form]);

  return (
    <Form form={form}>
      <Form.Item name='title'>
        <Input placeholder='Title' />
      </Form.Item>
      <Form.Item name='date'>
        <DatePicker format={"DD/MM/YYYY"} placeholder='Pick a date' />
      </Form.Item>
      <Form.Item name='time'>
        <TimePicker format={"HH:mm"} placeholder='Pick a date' />
      </Form.Item>
    </Form>
  );
}

export default Playground;

只提供了翻译的部分,没有包含其他内容。

英文:

Antd Datepicker & Timepicker accepts value of type moment (Antd v5 uses dayjs instead of moment). For Timepicker, you need to specify the format as second option in moment. moment(&#39;10:23:00&#39;, &#39;HH:mm&#39;)

Since you receive all values from backend and in order to set these values in form, you need to use useForm hook.

Here's the complete code that format and sets the values in form.

import moment from &quot;moment&quot;;
import { useEffect } from &quot;react&quot;;
import { Form, DatePicker, TimePicker, Input } from &quot;antd&quot;;

export function Playground() {
  const [form] = Form.useForm();

  useEffect(() =&gt; {
    // Get data from backend....
    const response = {
      title: &quot;Title&quot;,
      date: &quot;2023-12-05&quot;,
      time: &quot;10:23:00&quot;,
    };

    form.setFieldsValue({
      ...response,
      date: moment(response.date),
      time: moment(response.time, &quot;HH:mm&quot;),
    });
  }, [form]);

  return (
    &lt;Form form={form}&gt;
      &lt;Form.Item name=&#39;title&#39;&gt;
        &lt;Input placeholder=&#39;Title&#39; /&gt;
      &lt;/Form.Item&gt;
      &lt;Form.Item name=&#39;date&#39;&gt;
        &lt;DatePicker format={&quot;DD/MM/YYYY&quot;} placeholder=&#39;Pick a date&#39; /&gt;
      &lt;/Form.Item&gt;
      &lt;Form.Item name=&#39;time&#39;&gt;
        &lt;TimePicker format={&quot;HH:mm&quot;} placeholder=&#39;Pick a date&#39; /&gt;
      &lt;/Form.Item&gt;
    &lt;/Form&gt;
  );
}

export default Playground;

huangapple
  • 本文由 发表于 2023年5月17日 22:30:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定