添加到目前为止的序数信息

时间:2016-04-03 17:32:06

标签: javascript html

有点新的JavaScript,我正在尝试将序数信息添加到日期,例如4月4日我希望4月4日我只是使用下面的代码来获取日期编号,我将添加什么来获取序数信息

//Date
var d = new Date();
var n = d.getDate();    
document.getElementById("date").innerHTML = n;

2 个答案:

答案 0 :(得分:2)

我相信这只是该序数的英文短语中最右边的两个字母。由于你只对1到31之间的数字感兴趣,我只使用日期作为数组的索引:

var ordinalNames = [ "", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth", "sixteenth", "seventeenth", "eighteenth", "nineteenth", "twentieth", "twenty-first", "twenty-second", "twenty-third", "twenty-fourth", "twenty-fifth", "twenty-sixth", "twenty-seventh", "twenty-eighth", "twenty-ninth", "thirtieth", "thirty-first" ];

var d = new Date();
var n = d.getDate();    
document.getElementById("date").innerHTML = n + ordinalNames[n].slice(-2);

答案 1 :(得分:0)

有一种模式,你可以用它来制作一个功能

function nth(date) {
  if(date>=4 && date<=20) return 'th';
  switch (date % 10) {
        case 1:  return "st";
        case 2:  return "nd";
        case 3:  return "rd";
        default: return "th";
    }
}