如何将Datepicker格式从YYYY/MM/DD改为YYYY-MM-DD适配MySQL?
No problem at all! You just need to configure the dateFormat option in your jQuery UI Datepicker initialization to output the exact format MySQL expects. Here's how to do it step by step:
Step 1: Ensure Required Scripts Are Loaded
First, confirm your page includes both jQuery and jQuery UI JavaScript files (you already have the CSS linked, so this is the critical missing piece if you haven't added it yet):
<head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.12.4.js"></script> <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head>
Step 2: Initialize Datepicker with Correct Format
Add this script block (either in the <head> or before the closing </body> tag) to set the date format to YYYY-MM-DD:
$(function() { // Replace "#your-datepicker-input-id" with the actual ID of your datepicker input field $("#your-datepicker-input-id").datepicker({ dateFormat: 'yy-mm-dd' // This generates dates in YYYY-MM-DD format }); });
Key Details:
yy: Stands for the 4-digit year (e.g., 2024)mm: Represents the 2-digit month (e.g., 05 for May)dd: Represents the 2-digit day (e.g., 15)- The hyphens (
-) separate these components exactly as MySQL'sDATEdata type requires.
Once configured, whenever a user selects a date, the input field's value will automatically be in YYYY-MM-DD format. You can then directly use this value in your PHP code to insert into MySQL without needing extra string manipulation.
内容的提问来源于stack exchange,提问作者user7690205

