Abbreviated relative time (Instagram style) using momentjs language wise dynamic?

风流意气都作罢 提交于 2020-01-07 06:40:20

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!