[英]How can I change the date format in multiple divs using Jquery?
I am pulling an RSS feed
onto my site which contains a date in the format dd/mm/yyyy (UK date format)
. 我将
RSS feed
拉到我的站点上,其中包含dd/mm/yyyy (UK date format)
。 The dates are wrapped in h3 tags
, I would like to replace the original date with 2 divs containing only the date and the month respectively. 日期包装在
h3 tags
,我想用分别仅包含日期和月份的2个div替换原始日期。 I've managed to achieve this but the date outputted is the same for every instance. 我设法实现了这一点,但是每个实例的输出日期都相同。
How can I replace the date in each respective div? 如何在每个div中替换日期? I've tried all sorts but I can't quite figure it out.
我已经尝试了各种各样的方法,但是我不太清楚。 No doubt there is a far simpler way to do it!
毫无疑问,有一种更简单的方法! Any help is greatly appreciated.
任何帮助是极大的赞赏。
The HTML is: HTML是:
<div class='news'>
<h2>Title</h2>
<h3>11/06/2013</h3>
<p>Content</p>
</div>
<div class='news'>
<h2>Title</h2>
<h3>07/06/2013</h3>
<p>Content</p>
</div>
And the javascript is: 而JavaScript是:
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]; // Define month names array
$(".news h3").each(function () {
// Gets date and puts it in variable 'postDate'
var postDate = $(this).html();
// Reformats date into UK format after Javascript date object is created
var d = new Date(postDate.split('/')[2], postDate.split('/')[1] - 1, postDate.split('/')[0]);
$('.news h3').replaceWith('<div class="blogDate">' + d.getDate() +
'</div><div class="blogMonth">' + monthNames[d.getMonth()] +
'</div>'); //Replaces original date with newly created divs
});
I've created a JSFiddle so you can see the output . 我创建了一个JSFiddle,因此您可以看到输出。 The bottom date should read
7 Jun
. 最底日期应为
7 Jun
。
You need to replace the content of the current h3
instead of replacing all 您需要替换当前
h3
的内容,而不是替换所有
$(this).replaceWith('<div id="blogDate">' + d.getDate() + '</div><div id="blogMonth">' + monthNames[d.getMonth()] + '</div>');
More correct fix 更正确的修复
$(".news h3").replaceWith(function(){
var postDate = $(this).html();
var parts = postDate.split('/');
var d = new Date(parts[2], parts[1] - 1, parts[0]);
return '<div id="blogDate">' + d.getDate() + '</div><div id="blogMonth">' + monthNames[d.getMonth()] + '</div>';
})
If you can include a date-time library momentjs then 如果可以包含日期时间库momentjs,则
$(".news h3").replaceWith(function(){
var text = moment($.trim($(this).text()), "DD/MM/yyyy").format('D MMM');
return '<div>' + text + '</div>';
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.