Skip to content

Instantly share code, notes, and snippets.

@Gaurav8757
Created March 8, 2025 10:51
Show Gist options
  • Save Gaurav8757/d1c19c34ca0532ce501bb3c371dd2ee3 to your computer and use it in GitHub Desktop.
Save Gaurav8757/d1c19c34ca0532ce501bb3c371dd2ee3 to your computer and use it in GitHub Desktop.
Date yyyy-mm-dd select, show in value dd/MM/yyyy
// Date Format Helper Functions
const formatDate = (dateString, format = "dd/MM/yyyy") => {
if (!dateString) return ""; // Handle empty date
const date = new Date(dateString);
if (isNaN(date.getTime())) return "Invalid Date"; // Check if date is valid
const day = String(date.getDate()).padStart(2, "0");
const month = String(date.getMonth() + 1).padStart(2, "0"); // Months are zero-based
const year = date.getFullYear();
if (format === "yyyy-MM-dd") {
return `${year}-${month}-${day}`; // For input field yyyy-mm-dd
}
return `${day}/${month}/${year}`; // For Redux dd/mm/yyyy
};
export default formatDate;
const [selectedDate, setSelectedDate] = useState(formatDate(new Date(),"yyyy-MM-dd")); // Uncontrolled or extra state default current date
// HandleDateChange
const handleDateChange = (e) => {
const dateValue = e.target.value;
setSelectedDate(dateValue); //default date value yyyy-mm-dd
const formattedDateForRedux = formatDate(dateValue, "dd/MM/yyyy"); // dd/MM/yyyy format change from DateHelpers Above code
dispatch(magmaQuotes({ field: "ProposalDate", value: formattedDateForRedux }));
setValue("ProposalDate", formattedDateForRedux);
};
// text fields
<input
type="date"
onChange={handleDateChange}
value={selectedDate} //default value show or uncontrolled state yyyy-mm-dd
className={`flex w-full border rounded ${
selectedDate ? "border-red-500" : "border-gray-300"
}`}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment