简体   繁体   中英

How can i store the Ant Design's Time Picker time?

This is the time picker:

<TimePicker
          defaultValue={moment("12:08", format)}
          format={format}
          placeholder="Horário"
        />

I tried something like

const [time, setTime] = useState("");

And at the time picker

onChange={(e) => setTime(e.target.value)}

But it just returns an empty string

onChange have the following type.

onChange?: ((value: moment.Moment | null, dateString: string) => void) | undefined

The first parameter have the type Moment & second one is string. You can get the time from the second parameter and store it in state or if you want to customize time before storing it somewhere, you can use moment type value, apply any custom logic. You are trying to get value using e.target.value . It's onChange parameter are different as compare to normal field. Hope this solve your problem

Complete Code

import moment from 'moment';
import { useState } from 'react';
import { TimePicker } from 'antd';

const format = 'HH:mm';

export default function App() {
    const [time, setTime] = useState('12:08');

    return (
        <TimePicker
            format={format}
            value={moment(time, format)}
            placeholder='Horário'
            // onChange?: ((value: moment.Moment | null, dateString: string) => void) | undefined
            onChange={(value, dateString) => {
                console.log('Time', value, dateString);
                setTime(dateString);
            }}
        />
    );
}

You need dayJs if you want to manipulate time.

      onChange={(time, timeString) => {
        console.log(time, timeString);
        let test = dayjs(time);
        console.log("test", test.format());
        // "2022-12-06T03:00:00+05:00"
      }}

Install: https://day.js.org/docs/en/installation/node.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM