i have textfield with type=time , it takes an input in "hh:mm AM/PM" but sending value in just "hh:mm" format
check here
how to send input in the same format that user typed in textfield ?
code for input field
<TextField
sx={{
'& input[type="time"]::-webkit-calendar-picker-indicator': {
filter:
"invert(78%) sepia(66%) saturate(6558%) hue-rotate(84deg) brightness(27%) contrast(16%)",
paddingRight: "8px",
},
}}
name="startTime"
type="time"
id="startTime"
value={values.startTime}
onChange={handleChange}
/>
code for handling and sending time value
const initialValues = { startTime: "" };
const { values, errors, touched, handleBlur, handleChange,
handleSubmit } =
useFormik({
enableReinitialize: true,
initialValues,
onSubmit: async (values, action) => {
try {
let response = await axios.patch(
`${state.baseUrl}plan`,
{start_time: values.startTime},
);
}
It looks like you are using the native input type="time"
. And it would always return the time in 24 hours format, even if the visible value is in 12 hours format.
That is if you choose 11:59 PM
in the input, the value you would get will be "23:59" which is the 24 hours format. This is a limitation of the native time input.
More details at: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time#time_value_format
So in this case you would need to manually convert the 24 hours format time string to 12 hours time string.
const convert24to12 = (time) => {
// Extract hours and minutes from the time string
const hours = parseInt(time.slice(0, 2));
const minutes = time.slice(3, 5);
// Determine AM or PM
const amOrPm = hours >= 12 ? 'PM' : 'AM';
// Convert hours to 12-hour format
const twelveHourTime = `${(hours % 12) || 12}:${minutes} ${amOrPm}`;
return twelveHourTime;
}
<TextField
//other props
onChange={e => {
const 12hourString = convert24to12(e.target.value);
// Using setFieldValue from formik
setFieldValue("startTime", 12hourString)
}}
/>
A better solution would be to use a custom time picker from which you can output the time. I see you are using MUI, which already provides a nice time picker component here: https://mui.com/x/react-date-pickers/getting-started/.