José Carlos
José Carlos

Reputation: 774

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

Upvotes: 1

Views: 3052

Answers (2)

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

Upvotes: 0

Nouman Rafique
Nouman Rafique

Reputation: 849

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

Upvotes: 3

Related Questions