Reputation: 681
I'm beginner in ReactJS and I'm trying to save some dates fields.
By default, the dates are save in format yyyy-MM-dd
, but when I able to send the date for the API the format should be in format dd/mm/yyyy
.
I already try using .toLocaleDateString('pt-BR', {timeZone: 'UTC'});
. But when I did that, return error:
The specified value "19/8/2020" does not conform to the required format, "yyyy-MM-dd".
Here's my code I put in CodeSandBox
And, here where I get the date values:
import React, { useState } from "react";
const NewUser = () => {
const [data, setData] = useState({
birthdate: "",
admission_date: ""
});
const changeField = (field, value) => {
const auxData = { ...data };
auxData[field] = value;
setData(auxData);
};
return (
<div>
<span>Born</span>
<input
id="birthdate"
type="date"
value={data.birthdate}
onChange={(event) => changeField("birthdate", event.target.value)}
/>
<div />
<span>Admission Date</span>
<input
id="admission_date"
type="date"
value={data.admission_date}
onChange={(event) => changeField("admission_date", event.target.value)}
/>
</div>
);
};
export default NewUser;
Upvotes: -1
Views: 8601
Reputation: 20821
Don't import the entire momentjs library just for this simple task.
// yyyy-MM-dd
const input = "2020-08-19"
const [year, month, day] = input.split('-')
// dd/mm/yyyy
console.log(`${day}/${month}/${year}`)
// yyyy-MM-dd
const input = "2020-08-19"
const date = new Date(input)
// output depends on user's language and locale
console.log(new Intl.DateTimeFormat().format(date));
Also, check out You-Dont-Need-Momentjs for some lighter alternatives, and even some native methods for common use cases of handling dates.
Also, you probably want to wait until you're ready to send the data to the server before applying the transformation (instead of trying to do this inside changeField
). Example:
Upvotes: 5