JohnBoy
JohnBoy

Reputation: 63

Convert date day (05/12/2011 to 12th)

I am trying to covert the date to the day number followed by "st", "nd", "rd" or "th depending on the day. I am new to javascript so have no idea where to start.

E.g.

05/01/2011 = 1st
05/02/2011 = 2nd
05/03/2011 = 3rd
05/12/2011 = 12th
05/22/2011 = 22nd

Thanks

Upvotes: 6

Views: 4366

Answers (5)

Sir Kettle
Sir Kettle

Reputation: 127

I wrote this simple function the other day. Although for a date you don't need the larger numbers, this will cater for higher values too (1013th, 36021st etc...)

var fGetSuffix = function(nPos){

    var sSuffix = "";

    switch (nPos % 10){
        case 1:
            sSuffix = (nPos % 100 === 11) ? "th" : "st";
            break;
        case 2:
            sSuffix = (nPos % 100 === 12) ? "th" : "nd";
            break;
        case 3:
            sSuffix = (nPos % 100 === 13) ? "th" : "rd";
            break;
        default:
            sSuffix = "th";
            break;
    }

    return sSuffix;
};

Upvotes: 1

user578895
user578895

Reputation:

var date = new Date('05/12/2011').getDate(),
 ordinal = date + (date>10 && date<20 ? 'th' : {1:'st', 2:'nd', 3:'rd'}[date % 10] || 'th');

or

ordinal = date + ( [,'st','nd','rd'][/1?.$/.exec(date)] || 'th' );

Upvotes: 9

Alnitak
Alnitak

Reputation: 339955

First, get the date:

 var date = myval.getDate();

Then find the suffix:

 function get_nth_suffix(date) {
   switch (date) {
     case 1:
     case 21:
     case 31:
        return 'st';
     case 2:
     case 22:
        return 'nd';
     case 3:
     case 23:
        return 'rd';
     default:
        return 'th';
   }
 }

demo at http://jsfiddle.net/DZPSw/

Upvotes: 10

mellamokb
mellamokb

Reputation: 56779

You might start with JavaScript Date/Time Functions to get the Day number:

var theDate = myDateObj.GetDate(); // returns 1-31

Then you will need to write a rule to get the proper suffix. Most of the time it will be th, except for the exceptions. What are the exceptions? 1, 21, 31 = st, 2, 22 = nd, 3, 23 = rd, everything else is th. So we can use mod % to check if it ends in 1, 2, or 3:

var nth = '';
if (theDate > 3 && theDate < 21)    // catch teens, which are all 'th'
    nth = theDate + 'th';
else if (theDate % 10 == 1)         // exceptions ending in '1'
    nth = theDate + 'st';
else if (theDate % 10 == 2)         // exceptions ending in '2'
    nth = theDate + 'nd';
else if (theDate % 10 == 3)         // exceptions ending in '3'
    nth = theDate + 'rd';
else
    nth = theDate + 'th';           // everything else

Here's a working demo showing the endings for 1-31: http://jsfiddle.net/6Nhn8/

Or you could be boring and use a library :-)

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039278

You could do this easily with datejs using the S format specifier.

Upvotes: 0

Related Questions