使用JQuery格式化段落日期为指定格式的问题求助
解决方案
你的代码存在几个核心问题导致失效:
- 原生JS字符串没有内置的
.format()方法,jQuery对象也默认不带.formatDate()方法(除非额外引入jQuery UI这类扩展插件) - 选择器不匹配:原HTML用的是
post-time类,但代码里写的是post-time1/post-time2,且new-date元素在原HTML中根本不存在 - 直接用
new Date()解析04/11/2022会出错——JS默认把斜杠分隔的日期识别为MM/DD/YYYY格式,会错误解析成4月11日,而非你需要的11月4日
下面是两种无需额外插件的可行实现方案:
方法1:使用原生Intl.DateTimeFormat(推荐,支持多语言本地化)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <span class="post-time"> <p>04/11/2022</p> </span> <script> $(document).ready(function() { // 批量处理所有带post-time类的日期元素 $(".post-time p").each(function() { // 获取原日期文本并去除多余空格 const dateStr = $(this).text().trim(); // 按原格式DD/MM/YYYY拆分日、月、年 const [day, month, year] = dateStr.split('/'); // 创建正确的Date对象(注意JS月份是0起始,需减1) const date = new Date(year, month - 1, day); // 格式化为目标的MMM D, YYYY格式(en-US本地化对应英文月份缩写) const formattedDate = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric' }).format(date); // 替换原日期文本 $(this).text(formattedDate); }); }); </script>
方法2:手动定义月份缩写(兼容非常老旧的浏览器)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <span class="post-time"> <p>04/11/2022</p> </span> <script> $(document).ready(function() { // 定义英文月份缩写数组 const monthAbbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; $(".post-time p").each(function() { const dateStr = $(this).text().trim(); const [day, month, year] = dateStr.split('/'); // 匹配对应月份的缩写(索引减1对应数组位置) const monthName = monthAbbr[parseInt(month) - 1]; // 拼接成目标格式 const formattedDate = `${monthName} ${parseInt(day)}, ${year}`; $(this).text(formattedDate); }); }); </script>
关键注意点
- 必须严格按照原日期格式拆分:你的原日期是
DD/MM/YYYY(日/月/年),所以拆分顺序是日、月、年,创建Date对象时月份必须减1 - 两种方案都会直接替换原日期的文本内容,不需要额外新增
new-date元素 - 如果页面中有多个日期元素,
.each()可以批量处理所有目标日期
内容的提问来源于stack exchange,提问作者user2945884
相关产品推荐
相关产品推荐

