Extract a date suffix with MomentJS to make it sup

2019-02-12 20:16发布

问题:

I'm following strict user interface guidelines and I need to display date suffixes in superscript (<sup>):

18th September 2015

MomentJS has a lot of functions for formatting dates, but unfortunately it doesn't seem to allow us to extract a date suffix (the th bit in the example above) without including the number before it...

                Token    Output
Month           Mo       1st 2nd ... 11th 12th
Day of Month    Do       1st 2nd ... 30th 31st
Day of Year     DDDo     1st 2nd ... 364th 365th
...

Currently I'm stripping the numeric values before the suffix by using:

date.format("Do").replace(/\d/g, "");
--> "18th" -> "th"

But the problem is that this gets messy when having to display things like "18th September 2015", as I'm having to use three separate format() calls:

var dateSuffix = "<sup>" + date.format("Do").replace(/\d/g, "") + "</sup">;
date.format("DD") + dateSuffix + date.format("MMMM YYYY");
--> "18<sup>th</sup> September 2015"

I'm ideally looking to avoid using replace() altogether and to instead use something similar to this but with the Do part replaced with just the suffix:

moment(new Date()).format("DD<\\sup>Do</\\sup> MMMM YYYY");
--> "18<sup>18th</sup> September 2015"

Does MomentJS have any functionality to pull a date suffix by itself?

回答1:

I don't think MomentJS has the function you're looking for; I'd say you should go to the MomentJS site and submit it as a feature suggestion. You never know, it might even get implemented.

In the meanwhile, an alternative option might be to use the configuration options in MomentJS to change the Ordinal strings (ie the suffixes) so that they include a <sup> tag.

See the relevant section in the MomentJS manual here: http://momentjs.com/docs/#/customization/ordinal/

You'd end up writing a function that looks like this:

moment.locale('en', {
    ordinal : function (number, token) {
        var b = number % 10;
        var output = (~~ (number % 100 / 10) === 1) ? 'th' :
            (b === 1) ? 'st' :
            (b === 2) ? 'nd' :
            (b === 3) ? 'rd' : 'th';
        return number + '<sup>' + output + '</sup>';
    }
});

The above example is lifted directly from MomentJS's manual, with just the return line being modified.



回答2:

I looked at this for my own project, but decided to go with a regex solution.

myDate.format( 'Do MMMM YYYY' ).replace( /(\d)(st|nd|rd|th)/g, '$1<sup>$2</sup>' );

I appreciate the OP wanted to avoid regex, but this is a simple solution that may be beneficial to others.



回答3:

D DD        1..31       Day of month
Do          1st..31st   Day of month with ordinal
DDD DDDD    1..365      Day of year

You can use Do for a day with ordinal.

I use:

moment().format('Do MMMM YYYY');