【问题标题】:How to use Jquery to re-format an html date output如何使用 Jquery 重新格式化 html 日期输出
【发布时间】:2013-11-22 14:38:54
【问题描述】:
我有一个网站输出如下日期......
<div class="day">Starting November 22 2014, 08:40 AM</div>
这个页面输出不能在服务中改变,所以我只能使用客户端的方法来修改它。使用 jquery 如何将其解析为以下输出之一?
<div class="day">Nov 22nd, 8:40am</div>
<div class="day">11/22, 8:40am</div>
【问题讨论】:
标签:
jquery
date
content-management-system
format
【解决方案1】:
fiddle Demo
$('.day').text(function (_, txt) {
d = new Date(txt.replace('Starting ', ''));
return d.getMonth() + 1 + '/' + d.getDate() + ', ' + d.getHours() + ':' + d.getMinutes()+' '+txt.slice(-2);
});
输出
<div class="day">11/22, 8:40 AM</div>
【解决方案2】:
function nth(d) {
return ( [,'st','nd','rd'][/1?.$/.exec(d)] || 'th' );
}
function month(m) {
return ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][m];
}
function time(d) {
var hours = d.getHours();
var minutes = d.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var date = new Date($('.day').text()),
d1 = month(date.getMonth()) + ' ' + date.getDate() + nth(date.getDate()) + ', ' + time(date),
d2 = (date.getMonth() + 1) + '/' + date.getDate() + ', ' + time(date);
FIDDLE