'Convert Date from MMM dd yyy to dd/mm/yyyy and vice versa
I am using a native material-ui date picker which by default displays dates in the dd/mm/yyy format. I need to be able to display dates like this: Jun 18 2012 12:00AM. That is how dates are stored in my database and it cannot be changed for continuity. After pulling from the database, all other information is populated into textFields and Select boxes, but the date fields are left empty. Picking a date works just fine with no errors. Is it possible to convert Jun 18 2021 into 18/06/2012 and then the opposite when pushing back to the database?
if (row?.FieldType === "Date") {
return (
<TextField
type="date"
value={row?.Value || null}
onChange={(e) => {
setDetails((prev) => {
const update = [...prev.fields];
update[index] = {
...update[index],
Value: e.target.value,
};
return { ...prev, fields: update };
});
}}
variant="outlined"
margin="normal"
label={row["FieldName"]}
InputLabelProps={{
shrink: true,
}}
/>
);
}
This is how I am getting my data:
const [details, setDetails] = useState("");
const fetchDetails = async () => {
setBusy(true);
setDetails(await fetch(`/fiscalyears/FY2023/intakes/${params.id}/details`).then((response) => response.json()));
setBusy(false);
};
This is how I determine which data is a Select, textField, or Date:
<Box>
{details["fields"]?.map((row, index) => {
if (row?.FieldType === "Text" || row?.FieldType === "Decimal" || row?.FieldType === "Number") {
return (
<TextField value={dateInNumbers || ""} />
);
}
if (row?.FieldType === "Date") {
return (
<TextFieldtype="date"
format="MMM/dd/yyyy"
value={row?.Value || null}
onChange={(e) => {
setDetails((prev) => {
const update = [...prev.fields];
update[index] = {...update[index],
Value: e.target.value,
};
return { ...prev, fields: update };
});
}}
InputLabelProps={{ shrink: true, }}
/>);
} else {
return (
<TextField
value={row?.Value || ""}
variant="outlined"
margin="normal"
select
>
{row?.Choices.map((choice) => (
<MenuItem key={choice} value={choice}>
{choice}
</MenuItem>
))}
</TextField>
);
}
})}
</Box>
Solution 1:[1]
You can try something like this...
const inputDate = "Jun 18 2021";
const outputDate = new Date(Date.parse(inputDate)).toLocaleString("en-GB");
console.log(outputDate.slice(0, 10));
output: 18/06/2021
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohsen Alyafei |
