Getting the number ordinal with Moment.js

I don't think Moment.js provides such an interface because it's use case is very limited.

If you don't have a date (e.g. a ranking) you could use the following:

function ordinal(number) {
  switch (number) {
    case 1:
    case 21:
      return number + 'st';
      break;
    case 2:
    case 22:
      return number + 'nd';
      break;
    case 3:
    case 23:
      return number + 'rd';
      break;
    default:
      return number + 'th';
  }
}

EDIT: Answer to the edited question:

You can do the following:

const date = '3-12-2015';
moment(date, 'DD-MM-YYYY').format('Do');

Demo

Documentation:

Parse: http://momentjs.com/docs/#/parsing/string-format/

Display: http://momentjs.com/docs/#/displaying/format/


moment.localeData().ordinal(23)  

// 23rd

Building off of the accepted answer above, you can avoid adding the day to an arbitrary date and instead just do:

moment('3', 'DD').format('Do');

EDIT

As pointed out in the comments, the above answer will return an invalid date for any number above 30, so a more stable solution that includes the 31st would be:

moment(`2012-10-${day}`).format('Do')

Tags:

Momentjs