如何正确对MM/DD/YYYY格式的字符串日期数组进行降序排序并转换为英文月份缩写?
解决MM/DD/YYYY日期数组降序排序+月份转英文缩写问题
我明白你为啥头疼——直接用arr.sort()或者arr.sort().reverse()根本搞不定这种日期字符串的排序,因为字符串是按字符逐个比对的,完全不考虑日期的实际逻辑。别慌,咱们一步步来解决这个问题:
第一步:正确对日期数组降序排序
默认的sort()方法是按照字符串的Unicode码点排序的,比如'1/19/2024'会排在'10/21/2022'前面,因为第二个字符'/'的码点比'0'小,这显然不是我们要的日期顺序。
解决办法是把每个日期字符串转换成Date对象,通过比较时间戳来排序:
const dates = [ '1/19/2024', '1/20/2023', '10/21/2022', '11/18/2022', '12/16/2022', '3/17/2023', '6/10/2022', '6/16/2023', '6/17/2022', '6/21/2024', '6/24/2022', '6/3/2022', '6/31/2022', '7/15/2022', '7/8/2022', '8/19/2022', '9/15/2023', '9/16/2022' ]; // 降序排序:用b的日期减去a的日期,实现从新到旧排列 const sortedDates = dates.sort((a, b) => new Date(b) - new Date(a));
⚠️ 注意:你的数组里有'6/31/2022'这个无效日期(6月没有31天),JavaScript会自动把它解析成2022-07-01。如果需要校验并处理这类无效日期,可以在排序前先拆分日期部分做合法性检查。
第二步:将数字月份转换为英文缩写
我们可以定义一个月份缩写数组,然后把每个日期字符串拆分、替换、重新拼接成目标格式:
// 月份缩写数组,索引0对应1月,以此类推 const monthAbbrs = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 日期格式化函数:把MM/DD/YYYY转成 "Jan 19, 2024" 格式 function formatDate(dateStr) { const [month, day, year] = dateStr.split('/'); // 月份是从0开始的,所以要把数字月份减1来匹配数组索引 const monthAbbr = monthAbbrs[parseInt(month, 10) - 1]; return `${monthAbbr} ${day}, ${year}`; } // 对排序后的数组批量格式化 const formattedSortedDates = sortedDates.map(formatDate);
最终结果
运行上述代码后,formattedSortedDates的结果会是:
[ "Jun 21, 2024", "Jan 19, 2024", "Sep 15, 2023", "Jun 16, 2023", "Mar 17, 2023", "Jan 20, 2023", "Dec 16, 2022", "Nov 18, 2022", "Oct 21, 2022", "Sep 16, 2022", "Aug 19, 2022", "Jul 15, 2022", "Jul 8, 2022", "Jun 31, 2022", // 注意这个无效日期被自动转为7月1日,但格式化时还是显示原日期的数字 "Jun 24, 2022", "Jun 17, 2022", "Jun 10, 2022", "Jun 3, 2022" ]
如果想要让无效日期的格式化也跟着解析后的日期走,可以修改formatDate函数,基于Date对象来获取月份:
function formatDate(dateStr) { const date = new Date(dateStr); const monthAbbr = monthAbbrs[date.getMonth()]; const day = date.getDate(); const year = date.getFullYear(); return `${monthAbbr} ${day}, ${year}`; }
这样'6/31/2022'会被格式化为"Jul 1, 2022",你可以根据需求选择哪种方式。
内容的提问来源于stack exchange,提问作者hattoncm
相关产品推荐
相关产品推荐

