1 | import React, { ChangeEventHandler, useState } from "react";
|
2 |
|
3 | import { setHours, setMinutes } from "date-fns";
|
4 | import { DayPicker } from "react-day-picker";
|
5 |
|
6 | export function InputTime() {
|
7 | const [selected, setSelected] = useState<Date>();
|
8 | const [timeValue, setTimeValue] = useState<string>("00:00");
|
9 |
|
10 | const handleTimeChange: ChangeEventHandler<HTMLInputElement> = (e) => {
|
11 | const time = e.target.value;
|
12 | if (!selected) {
|
13 | setTimeValue(time);
|
14 | return;
|
15 | }
|
16 | const [hours, minutes] = time.split(":").map((str) => parseInt(str, 10));
|
17 | const newSelectedDate = setHours(setMinutes(selected, minutes), hours);
|
18 | setSelected(newSelectedDate);
|
19 | setTimeValue(time);
|
20 | };
|
21 |
|
22 | const handleDaySelect = (date: Date | undefined) => {
|
23 | if (!timeValue || !date) {
|
24 | setSelected(date);
|
25 | return;
|
26 | }
|
27 | const [hours, minutes] = timeValue
|
28 | .split(":")
|
29 | .map((str) => parseInt(str, 10));
|
30 | const newDate = new Date(
|
31 | date.getFullYear(),
|
32 | date.getMonth(),
|
33 | date.getDate(),
|
34 | hours,
|
35 | minutes
|
36 | );
|
37 | setSelected(newDate);
|
38 | };
|
39 |
|
40 | return (
|
41 | <div>
|
42 | <form style={{ marginBlockEnd: "1em" }}>
|
43 | <label>
|
44 | Set the time:{" "}
|
45 | <input type="time" value={timeValue} onChange={handleTimeChange} />
|
46 | </label>
|
47 | </form>
|
48 | <DayPicker
|
49 | mode="single"
|
50 | selected={selected}
|
51 | onSelect={handleDaySelect}
|
52 | footer={`Selected date: ${selected ? selected.toLocaleString() : "none"}`}
|
53 | />
|
54 | </div>
|
55 | );
|
56 | }
|