将st,th,rd添加到jQuery日期

时间:2016-05-20 19:47:27

标签: javascript jquery html css

我检查了与此类似的其他帖子,但我没有得到我需要的答案。

如何将这些字词添加到我的数字末尾?

这是我的jQuery代码:

var monthNames = [ "January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December" ];
        var dayNames= ["Sunday,","Monday,","Tuesday,","Wednesday,","Thursday,","Friday,","Saturday,"]

        var newDate = new Date();
        newDate.setDate(newDate.getDate());    
        $('#the-date').html(dayNames[newDate.getDay()] + " " + monthNames[newDate.getMonth()] + ' ' + newDate.getDate() + ' ' );

2 个答案:

答案 0 :(得分:0)

moment.js非常适合处理日期,并通过format提供。例如:

moment().format("MMM Do YY"); // May 20th 16

答案 1 :(得分:0)

来自this question

var suffix = "";
switch(inst.selectedDay) {
    case '1': case '21': case '31': suffix = 'st'; break;
    case '2': case '22': suffix = 'nd'; break;
    case '3': case '23': suffix = 'rd'; break;
    default: suffix = 'th';
}

像这样加入:

// below `newDate.setDate` line
var dateNumber = newData.getDate();
var suffix = "";
switch(dateNumber) {
    case '1': case '21': case '31': suffix = 'st'; break;
    case '2': case '22': suffix = 'nd'; break;
    case '3': case '23': suffix = 'rd'; break;
    default: suffix = 'th';
}
$('#the-date').html(dayNames[newDate.getDay()] + " " + monthNames[newDate.getMonth()] + ' ' + dateNumber + suffix + ' ' );