Reputation: 71
Kinda new to JavaScript and am trying to add ordinal information to dates e.g Instead April 4 I want April 4th currently im just using the code below to get the date number, what would I add to get ordinal info
//Date
var d = new Date();
var n = d.getDate();
document.getElementById("date").innerHTML = n;
Upvotes: 0
Views: 48
Reputation: 21
I believe it's just the rightmost two letters of the english phrase for that ordinal number. Since you're only interested in numbers between 1 and 31 I'd just use the date as an index into an array:
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);
Upvotes: 2
Reputation: 667
There is a pattern and you can make a function out of it
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";
}
}
Upvotes: 0