我使用 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"
}
});
我得到错误:
Cannot read property 'humanize' of undefined at Moment.from (moment.js:3313)
当我打电话
moment(value).fromNow()
这里,value是Date类型的日期
是否可以使用 moment.js 获得短格式版本?
最佳答案
我假设您的问题是格式字符串。我用了'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>
关于javascript - 如何更改 fromNow 调用的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45442501/