I'd like to use a short one in some places (eg {m: "1m"}
) and a long one in others (eg {m: "one minute"}
).
问题:
回答1:
I think the answer centres around what is documented here In short, tweak part of the locale to suit your needs using a function.
Here is a short sample:
var useshort = false;
moment.locale( 'en', {
relativeTime : {
future: "in %s",
past: "%s ago",
s: "seconds",
m: function (/* number, withoutSuffix, key, isFuture */) { 'use strict';
return useshort ? "1m" : "1 minute";
},
mm: "%d minutes",
h: "an hour",
hh: "%d hours",
d: "a day",
dd: "%d days",
M: "a month",
MM: "%d months",
y: "a year",
yy: "%d years"
}
});
console.log(moment().subtract(1, "minute").fromNow() ); // 1 minute ago
console.log(moment().subtract(2, "minute").fromNow() ); // 2 minutes ago
useshort = true;
console.log(moment().subtract(1, "minute").fromNow() ); // 1m ago
console.log(moment().subtract(2, "minute").fromNow() ); // 2 minutes ago
Since your need is about 'm', we can safely ignore the parameters (I think) as they are not suppose to change. I display the 2 minutes offset to show that we indeed only modified the behaviour of 'm'.
If this is too messy for you (using a variable from the scope of where the locale is set), an another option is, of course, to make your own local ('en-short') and simply hardcode the short value, then set the locale as you need. I chose this solution because I did not know how you had to make the decision of using one format vs the other.
To be complete, this relies on the fact that you know which locale needs to be manipulated. If the choice of locale is up to the end user, the problem becomes a bit more complex. In that case, all I can think of would be to retrieve the configuration of the current locale using moment.localeData()._relativeTime
and change the 'm' member to the function that works for you. You would still have to find out a way to express the 'm' and 'minute' units in the proper locale (not sure how to do that).
This solution is really a last resort as I don't know if _relativeTime
is a safe API over time (I would guess not).
Hope this helps.