2016-05-20 74 views
0

我檢查了與此類似的其他帖子,但沒有得到我需要的答案。將st,th,rd添加到jQuery日期

如何將這些單詞添加到我的數字末尾?

,這裏是我的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() + ' '); 
+6

你看到[這個問題和它的接受的答案](https://stackoverflow.com /問題/ 13627308 /添加-ST-ND-RD-和-TH-序後綴到一個數)?這似乎正是你需要的。 –

+0

我做了但不知道哪一個我應該使用.. – Chad

+0

雖然這[功能](https://ecommerce.shopify.com/c/ecommerce-design/t/ordinal-number-in-javascript-1st-2nd- 3rd-4th-29259)從其中一個答案看起來相當不錯 –

回答

0

moment.js日期處理是偉大的,通過format提供這一點。例如:

moment().format("MMM Do YY"); // May 20th 16 
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 + ' '); 
+0

如果案例中的字符串不起作用,請使用ints:'case 1:case 21:case 31:'等(與上面的代碼相同,只是沒有圍繞數字的引號。 – sander