React DatePicker组件dateFormat属性不生效问题及日期格式转换需求求助
dateFormat Not Returning Formatted String Hey there! I totally get where you're coming from—let's break down what's happening and fix this date formatting issue for your SQL table.
Why dateFormat Isn't Changing Your Output
First, a quick key clarification: the dateFormat prop in React DatePicker only controls how the date is displayed to users in the input field. It doesn't alter the type of value returned by the onChange callback—this will always be a native JavaScript Date object, which is why your console.log shows something like Fri Dec 31 2021 18:10:31 GMT+0530 (India Standard Time).
Two Reliable Solutions to Get yyyy-MM-dd for SQL
1. Quick Built-in JavaScript Method
If you want to avoid extra dependencies, you can use JavaScript's native toISOString() method to extract the yyyy-MM-dd format directly:
<DatePicker dateFormat='dd/MM/yyyy' selected={startDate} onChange={(date) => { setStartDate(date); // Extract the yyyy-MM-dd portion from the Date object const sqlFormattedDate = date.toISOString().split('T')[0]; console.log(sqlFormattedDate); // Output: "2021-12-31" // Use this string to insert into your SQL table }} />
2. Use Date-Fns (Recommended for Precision)
React DatePicker relies on the date-fns library under the hood, so you can import its format function for precise, edge-case-free formatting (no worrying about single-digit months/days missing leading zeros):
import { format } from 'date-fns'; // ... <DatePicker dateFormat='dd/MM/yyyy' selected={startDate} onChange={(date) => { setStartDate(date); // Format directly to yyyy-MM-dd for SQL const sqlDate = format(date, 'yyyy-MM-dd'); console.log(sqlDate); // Output: "2021-12-31" // Bonus: Grab the display-formatted string (dd/MM/yyyy) if needed const displayDate = format(date, 'dd/MM/yyyy'); console.log(displayDate); // Output: "31/12/2021" }} />
3. Get the Exact Displayed String (If Required)
If you specifically need the exact string shown in the DatePicker input (matching your dateFormat), use the onChangeRaw event to access the input's value directly:
<DatePicker dateFormat='dd/MM/yyyy' selected={startDate} onChange={(date) => setStartDate(date)} onChangeRaw={(e) => { // e.target.value is the formatted string from the input field console.log(e.target.value); // Output: "31/12/2021" // Convert this to yyyy-MM-dd for SQL if needed }} />
Final Note for SQL
The yyyy-MM-dd format is the standard for SQL DATE columns, so either of the first two methods will give you a string your database can accept directly.
内容的提问来源于stack exchange,提问作者Niresh

