如何将jqGrid日期选择器日期格式从mm/dd/yyyy转为yyyy/mm/dd并排序
Hey Klaus, let's work through how to switch your jqGrid date picker format to yyyy/mm/dd and get proper date sorting set up. It's straightforward once you know the right configs!
First, you need to adjust two key parts: the date picker itself (so it outputs dates in yyyy/mm/dd) and the column formatter (so the date shows correctly in the grid).
In your colModel configuration for the date column, add these settings:
colModel: [ // ... other columns { name: 'dateColumn', index: 'dateColumn', label: 'Date', width: 130, // Set up how the date is displayed in the grid formatter: 'date', formatoptions: { srcformat: 'yyyy/mm/dd', // Match the format coming from the picker/backend newformat: 'yyyy/mm/dd' // The format you want to show to users }, // Configure the date picker for editing edittype: 'text', editoptions: { dataInit: function(element) { $(element).datepicker({ dateFormat: 'yy/mm/dd', // jQuery UI datepicker uses 'yy' for 4-digit year changeYear: true, changeMonth: true, showButtonPanel: true }); } }, // ... sorting settings next } // ... other columns ]
Note: jQuery UI Datepicker uses its own format syntax—yy stands for 4-digit year, mm for 2-digit month, dd for 2-digit day. That's why we use yy/mm/dd there instead of yyyy/mm/dd.
By default, jqGrid sorts dates as strings, which can lead to unexpected order (especially if your original format was dd/mm/yyyy). To ensure proper chronological sorting, add these properties to your date column's colModel entry:
sorttype: 'date', sortrules: { dateFormat: 'Y/m/d' // jqGrid's syntax: Y=4-digit year, m=2-digit month, d=2-digit day }
This tells jqGrid to parse the date string into a proper Date object for sorting, so it orders dates by their actual chronological value instead of string order.
- Make sure you've included jQuery UI's Datepicker CSS and JS files—without them, the date picker won't render properly.
- If your backend returns dates in a different format (like ISO
yyyy-mm-dd), adjust thesrcformatinformatoptionsto match (e.g.,'Y-m-d'for ISO dates). - For server-side sorting: If you're letting the backend handle sorting, ensure your server parses the
yyyy/mm/dddate string correctly and sorts it as a date type instead of a string.
That should do it! Your date picker will now use yyyy/mm/dd, and the grid will sort dates exactly as you need.
内容的提问来源于stack exchange,提问作者Klaus

