I am using Material Ui DateTime picker in a form. After submitting the form, I get the following error:
Invalid Date Format
Image
I am using JSON Server in my react app for saving data.
This is the output Element for the DateTime picker on DOM.
<input aria-invalid="false" readonly="" type="text" class="MuiInputBase-input MuiInput-input" value="March 16th 08:50 a.m.">
This is data on db.json.
{
"text": "study",
"day": "2022-03-16T05:20:00.000Z",
"reminder": true,
"id": 1
}
This is my code for Add date.
import { useState } from "react";
import DateFnsUtils from "#date-io/date-fns";
import { MuiPickersUtilsProvider } from "#material-ui/pickers";
import "date-fns";
import { DateTimePicker } from "#material-ui/pickers";
const AddTask = ({ onAdd }) => {
const [day, setDay] = useState(new Date());
const onSubmit = (e) => {
e.preventDefault();
onAdd({ day });
setDay("");
};
return (
<form className="add-form" onSubmit={onSubmit}>
<div className="form-control">
<label>Day & time</label>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<DateTimePicker
disableToolbar
variant="inline"
value={day}
onChange={(day) => {
setDay(day);
}}
autoOk
/>
</MuiPickersUtilsProvider>
</div>
</form>
);
};
I would appreciate it if you help me. Thanks
It will probably not break if you remove the setDay(""); line from onSubmit. Why do you need it after all?
Related
I am passing a plain date as string from api, something like 2022-04-24, but on front react, it is parsing the date to the local timezone, which I don't want to be parsed to local timezone. My code on react looks like:
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "#hookform/resolvers/yup";
import * as Yup from "yup";
import ReactDatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
export function App() {
const schema = Yup.object({});
const {
register,
handleSubmit,
formState: { errors },
control
} = useForm({
resolver: yupResolver(schema)
});
const onSubmit = async (input) => {
console.log("input", input);
};
const item = {
id: 12,
release_date: "2022-04-24"
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
control={control}
name="release_date"
defaultValue={item.release_date ? new Date(item.release_date) : null}
render={({ field: { onChange, onBlur, value, ref } }) => (
<ReactDatePicker
onChange={onChange}
onBlur={onBlur}
className="form-control w-full"
dateFormat="MMM dd, yyyy"
selected={value}
/>
)}
/>
<input type="submit" />
</form>
);
}
Here is the screenshot,
Currently, it is showing apr 23, even when I had passed it 04-24. To see the issue, you might have to use some different timezone (where still current date is apr 23).
And, here is the sandbox
There is a different when you use - and /
const date1 = new Date("2022/04/24");
const date2 = new Date("2022-04-24");
document.getElementById("app").innerHTML = `
<h4>${date1}</h4>
<h4>${date2}</h4>
`;
<div id="app">
</div>
https://codesandbox.io/s/date-object-qqjnrs
Luxon implementation: (from the same people who build moment)
https://moment.github.io/luxon/#/?id=luxon
// leave it as a string
const date1 = "2022-04-24";
const date2 = "2022/04/24";
const date1Result = luxon.DateTime.fromFormat(date1, "yyyy-M-dd").toJSDate()
const date2Result = luxon.DateTime.fromFormat(date, "yyyy/M/dd").toJSDate()
console.log({date1Result, date2Result})
(note, in moment js the solution would be similar.)
You can see for yourself by going to the luxon website and writing these lines in the dev tools console.
https://moment.github.io/luxon/#/?id=luxon
I am working on a React application and currently have a date picker to select a date range using Ant Design. I want to store the value of the selected date into a variable that can be accessed by another file in my program. How can I bind the selected value into a variable? Here is the JavaScript code for my date picker:
<p>Select a date range: </p>
</div>
<div className="left">
<Space direction="vertical" size={12}>
<RangePicker
format="YYYY-MM-DD"
onChange={this.onChange}
onOk={onOk}
/>
</Space>
Check the following example, You can store the date values in a variable once the date is selected and onChange function is called.
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { DatePicker, Space } from 'antd';
import 'antd/dist/antd.css';
import './index.css';
const { RangePicker } = DatePicker;
const Demo = () => {
let selecteddate;
let selectedstartdate;
let selectedenddate;
const onChange = (value) => {
selecteddate = value;
selectedstartdate = value[0];
selectedenddate = value[1];
//Pass the following values
console.log("selecteddate:",selecteddate);
console.log("selectedstartdate:",selectedstartdate);
console.log("selectedenddate:",selectedenddate);
};
return (
<>
<p>Select a date range: </p>
<Space direction="vertical" size={12}>
<RangePicker format="YYYY-MM-DD" onChange={onChange} />
</Space>
</>
);
};
export default Demo
Screenshot
I'm trying to translate the component React DatePicker. But, I'm getting an error when trying to do this.
My code so far:
import DatePicker, { registerLocale } from 'react-datepicker';
const MONTHSDATE = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
const DAYSDATE = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'];
registerLocale('ptBR', {
localize: {
month: n => MONTHSDATE[n],
day: n => DAYSDATE[n]
},
formatLong: {}
});
<DatePicker
selected={realizedDateFrom}
onChange={(date) => setRealizedDateFrom(date)}
placeholderText={translate.t("activity_report_realized_from")}
className="MuiInputBase-root MuiFilledInput-root activity-report-datepicker"
dateFormat={'dd/MM/yyyy'}
showMonthDropdown
showYearDropdown
formatWeekDay={nameOfDay => nameOfDay.substr(0, 3)}
locale={translate.t("datapicker_translate")} //using translate getting word 'ptBR' for portuguese and 'en' for english
/>
When I change the language, this code works well just when i pick the date from calendar...
But when I try to write/input from the keyboard I get this error
The source code from this component is --> Project: https://github.com/Hacker0x01/react-datepicker
You can use date-fns for ptBR. (Basically, the error is because the calendar needs more translations than the one which you write).
So, the recommended is to use them from date-fns, one example would be:
import React from "react";
import DatePicker from "react-datepicker";
import { registerLocale } from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { en, ptBR } from "date-fns/locale";
registerLocale("ptBR", ptBR);
registerLocale("en", en);
export default function App() {
const [language, setLanguage] = React.useState("ptBR");
return (
<div className="App">
<h3>Change the Language ({language})</h3>
<DatePicker locale={language} />
<button onClick={() => setLanguage("ptBr")}>ptBr</button>
<button onClick={() => setLanguage("en")}>eng</button>
</div>
);
}
The example is running on CodeSandbox: https://codesandbox.io/s/empty-browser-yfvg7?file=/src/App.js
I have a datepicker and it shows a default value(shows only if the api has a value), when I update it, onchange function doesn't give the selected value. it gives the initial value which is coming from the api. any idea how I can get the updated value to onchange function.
api data
const apidata = my api
setState({
...state,
formData:{
...apidata,
startDate:moment(apidata.startDate).utc()
}
})
form component
<Form
name="update form"
initialValues={state.formData}
autoComplete="off"
form={form}
>
<Form.Item
label="Start Date"
name="startDate"
rules={[{ required: true, message: "Please enter value!!!!!" }]}
>
<DatePicker
value={state.formData?.startDate}
onChange={(date: any)=>updateFields(date)}
/>
</Form.Item>
</Form>
update function
const updateFields = (data:any) => { // here I'm getting the already set api value not the changed value
setState({
...state,
formData : {
startDate:data
}
})
}
The bug is not easy to find if you don't share a minimal reproducible example.
If you use the defaultValue from antd Datepicker API the onChange works as expected.
<DatePicker
defaultValue={moment('2015-01-01', 'YYYY-MM-DD')}
onChange={updateFields}
/>
Here is a small stackblitz which works as expected using antd Datepicker and Form.Item.
E.g.:
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Form, DatePicker } from 'antd';
import moment from 'moment';
const Demo = () => {
const [form] = Form.useForm();
function updateFields(date, dateString) {
console.log(date, dateString);
}
return (
<Form form={form} name="control-hooks">
<Form.Item name="DatePicker">
<DatePicker
defaultValue={moment('2015-01-01', 'YYYY-MM-DD')}
onChange={updateFields}
/>
</Form.Item>
</Form>
);
};
ReactDOM.render(<Demo />, document.getElementById('container'));
I am using material-UI datepicker which i followed the procedure but on event handler the date is not changing but the initial value is working fine which i give in useState. I want my datepicker to work smooth when i want to select my desire date. The example of Datepicker is also in the link
https://material-ui.com/components/pickers/#date-time-pickers
https://codesandbox.io/s/z9k3z
import {
KeyboardDatePicker,
MuiPickersUtilsProvider,
} from "#material-ui/pickers";
import DateFnsUtils from "#date-io/date-fns";
import React, { useState } from "react";
function AddCar() {
const [date, setDate] = useState(new Date());
const addCar = (e) => {
e.preventDefault();
console.log(date.toLocaleDateString());
setDate(new Date());
};
return (
<div className="addCar">
<div>
<form className="addCar__form" onSubmit={addCar}>
{/* Date */}
<div className="addCar__mainForm row ">
<div className="col-lg-3 col-md-6 col-sm-12 my-2">
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
disableToolbar
variant="inline"
format="MM-dd-yyyy"
margin="normal"
label="Select Date"
value={date}
onChange={(e) => setDate(date)}
KeyboardButtonProps={{
"aria-label": "change date",
}}
/>
</MuiPickersUtilsProvider>
</div>
</div>
<button type="submit" className="btn btn-success">
ADD CAR
</button>
</form>
</div>
</div>
);
}
export default AddCar;
You keep setting the same date from state.
const [date, setDate] = useState(new Date());
// ...
onChange={(e) => setDate(date)}
It should be:
onChange={(e) => setDate(e)}
The first parameter in DatePicker's onChange callback is the new date you've just input.
change this line
onChange={(e) => setDate(date)}
to
onChange={setDate}
Codesandbox: https://codesandbox.io/s/material-demo-forked-siueb?file=/addCar.js:939-957
You need to set the value like
onChange={(e) => setDate(e)}
Also, You don't need to set the state like this:
const [date, setDate] = useState(new Date());