toLocaleFormat替代方案咨询:Mozilla 58+下jQuery Datepicker兼容问题
toLocaleFormat Hey there! I see you're hitting a snag with jQuery Datepicker after upgrading Firefox to 58+—since toLocaleFormat got deprecated, your date formatting broke entirely. No worries though, we can swap it out with a standard, widely-supported API to get that dd-MMM-yyyy (like 16-May-2018) format you need.
The Root of the Issue
toLocaleFormat was a Firefox-only non-standard method, so once Mozilla removed it in v58+, your code lost its date formatting capability. The fix relies on Intl.DateTimeFormat, an ECMAScript standard API that works across all modern browsers (including Firefox 58+).
Custom Date Formatting Function
First, let's build a reusable function that converts a Date object into your desired string format:
function formatDate(date) { // Use en-US locale to ensure 3-letter English month abbreviations (e.g., May, Jan) const formatter = new Intl.DateTimeFormat('en-US', { day: '2-digit', month: 'short', year: 'numeric' }); // Extract and rearrange date components to match "dd-MMM-yyyy" const parts = formatter.formatToParts(date); const day = parts.find(part => part.type === 'day').value; const month = parts.find(part => part.type === 'month').value; const year = parts.find(part => part.type === 'year').value; return `${day}-${month}-${year}`; }
Updated Version of Your Code
Now replace all instances of toLocaleFormat('%d-%b-%Y') with calls to our formatDate function. Here's the full modified code:
// Replace toLocaleFormat with our custom function var today = formatDate(new Date()); var _todayPlus30Days = new Date(); _todayPlus30Days.setDate(_todayPlus30Days.getDate() + 29); _todayPlus30Days = formatDate(_todayPlus30Days); $('#creditLetterDateId').DatePicker({ format: 'd-M-Y', default_position: 'below', start_date: today, onSelect: function(d, i) { if (d !== i.lastVal) { $(this).change(); } } }).val(today); $("#creditLetterDateId").change(function() { var _dateStr = $(this).val().replace(/-/g, ' '); var _date = new Date(_dateStr); _date.setDate(_date.getDate() + 29); // Replace toLocaleFormat here too _date = formatDate(_date); $('#cardvalidityDateId').DatePicker({ format: 'd-M-Y', default_position: 'below', start_date: _date, onSelect: function(d, i) { if (d !== i.lastVal) { $(this).change(); } } }).val(_date); });
Why This Works
Intl.DateTimeFormatis a standardized API, so it’s supported in every modern browser (no more Firefox-specific dependencies).- The
en-USlocale guarantees month abbreviations are 3-letter English strings (exactly what your Datepicker expects). - Using
formatToPartslets us pull individual date components and rearrange them to match your exactdd-MMM-yyyyformat.
Quick Test
If you run formatDate(new Date('2018-05-16')), it’ll return 16-May-2018—perfect for your Datepicker setup!
内容的提问来源于stack exchange,提问作者manikanth avb

