Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the number ordinal with Moment.js

Tags:

momentjs

Is it possible to get a number's ordinal with Moment.js? For example if I pass in the number 7 and Momentjs would return '7th'

So far I have tried all these but none have worked

console.log(moment("12", "D Do")); // returns n {_isAMomentObject: true, _i: "12", _f: "D Do", _isUTC: false, _pf: Object…}
                console.log(moment("3", "D Do")); // returns n {_isAMomentObject: true, _i: "3", _f: "D Do", _isUTC: false, _pf: Object…}
                console.log(moment(3).format("D Do")); // returns '1 1st'
                console.log(moment('3').format("D Do")); // returns '1 1st'
                console.log(moment().day('3').format("Do")); // returns '9th'
                console.log(moment().day(3).format("D Do")); // returns '9 9th'

EDIT: I should have mentioned that I am trying to process a date. So I get the date in this format DD-MM-YYYY. So if the date is 07-12-2015, I want to display it as 7th.

like image 342
Jose the hose Avatar asked Dec 11 '15 16:12

Jose the hose


People also ask

What is Moment () in JavaScript?

Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.

Is MomentJS still used?

MomentJS is a widely used time and date formatting and calculation library.

Is MomentJS deprecated?

MomentJs recently announced that the library is now deprecated. This is a big deal for the javascript community who actively downloads moment almost 15 million times a week.

How do you add St after 1?

The rules are as follows: st is used with numbers ending in 1 (e.g. 1st, pronounced first) nd is used with numbers ending in 2 (e.g. 92nd, pronounced ninety-second) rd is used with numbers ending in 3 (e.g. 33rd, pronounced thirty-third)


1 Answers

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/

like image 83
Julius Rickert Avatar answered Sep 23 '22 22:09

Julius Rickert