如何更改fromNow调用的输出?

时间:2017-08-01 15:56:45

标签: javascript momentjs

我用moment.js来获得相对时间。例如,它返回" 6小时前"。但是我希望得到像" 6h"

这样的简短版本

我阅读了文档:http://momentjs.com/docs/#/customization/relative-time/

但如果我改变:

moment.updateLocale('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s ago",
        s  : 'a few seconds',
        ss : '%d seconds',
        m:  "a 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"
    }
});

moment.updateLocale('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s",
        s  : 'a few seconds',
        ss : '%d h',
        m:  "a minute",
        mm: "%d m",
        h:  "an hour",
        hh: "%d h",
        d:  "a day",
        dd: "%d d",
        M:  "a month",
        MM: "%d m",
        y:  "a year",
        yy: "%d y"
    }
});

我收到错误:

  

无法阅读财产'人性化'未定义的           在Moment.from(moment.js:3313)

当我打电话

moment(value).fromNow()

此处,value是日期类型

的日期

是否可以使用moment.js获得短格式版本?

1 个答案:

答案 0 :(得分:1)

我认为您的问题是格式字符串。我使用了' hh':



moment.updateLocale('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s ago",
        s  : 'a few seconds',
        ss : '%d seconds',
        m:  "a minute",
        mm: "%d minutes",
        h:  "an hour",
        hh: "%dh",
        d:  "a day",
        dd: "%d days",
        M:  "a month",
        MM: "%d months",
        y:  "a year",
        yy: "%d years"
    }
});

//
// compute six hours ago...
//
 var value = new Date();
value.setHours(value.getHours() - 6);


console.log('With \'hh\' format string: ' + moment(value).fromNow('hh'));
console.log('With no format: ' + moment(value).fromNow());

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
&#13;
&#13;
&#13;