问题
moment().startOf('day').fromNow() //3 days ago.
How can I change the above to show 3d instead of language is English and to "3 j" if language is french and so on dynamically change according to the language?
回答1:
You can use moment.locale method as reported in the docs. Remember that you have to import all locales you need or you can use moment-with-locales.js that provides all supported locales.
EDIT:
To customize format of momentjs fromNow method you can use updateLocale as documented in the Customize -> Relative time section of the docs.
moment.updateLocale('en',{
relativeTime : {
future: "in %s",
past: "%s",
s: "seconds",
m: "a minute",
mm: "%d minutes",
h: "an hour",
hh: "%d h",
d: "a day",
dd: "%d d",
M: "a month",
MM: "%d months",
y: "a year",
yy: "%d years"
}
});
moment.updateLocale('fr',{
relativeTime : {
future : 'dans %s',
past : '%s',
s : 'quelques secondes',
m : 'une minute',
mm : '%d minutes',
h : 'une heure',
hh : '%d heures',
d : 'un jour',
dd : '%d j',
M : 'un mois',
MM : '%d mois',
y : 'un an',
yy : '%d ans'
}
});
moment.locale('fr');
moment().subtract(2, 'days').startOf('day').fromNow() // 2 j
moment.locale('en');
moment().subtract(2, 'days').startOf('day').fromNow() // 2 d
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment-with-locales.js"></script>
来源:https://stackoverflow.com/questions/37536969/abbreviated-relative-time-instagram-style-using-momentjs-language-wise-dynamic