在moment.js的使用过程中,有时需要对moment的属性与方法进行扩展,以moment.duration的humanize方法为例:
// 设置时间长度为50周
var w50s = moment.duration(50, 'w').humanize()
// 结果输出为1年
console.log(w50s);
从上面的例子可以看出,moment.js特意设计的humanize方法虽然看起来很人性化,但是未必符合我们的国情,所以这时我们就需要实现自己的duration方法。
moment内部设计了很多类,核心moment的扩展方法如下:
// moment的扩展方法
moment.fn.toString = function() {
return this.format('LLLL');
}
// 测试当前时间
console.log(moment().toString())
// 输出结果:2017年7月14日星期五下午5点28分
核心Duration的扩展方法如下:
// 格式化时间间隔
moment.duration.fn.format = function() {
var units = [
{ years : '年' },
{ months : '个月'},
{ weeks : '周' },
{ days : '天' },
{ hours : '小时'},
{ minutes : '分钟'},
{ seconds : '秒'},
{ milliseconds : '微秒'}
],
result = [];
for(var i =0, len = units.length; i < len; i++) {
for(var prop in units[i]) {
var num = this._data[prop];
if(num > 0) {
result.push(num + units[i][prop])
}
}
}
return result.join(' ');
}
// 测试时间
console.log(moment.duration(500, 'd').format());
// 输出结果为1年 4个月 13天
结论
最后,附上moment.js的公开属性、方法的源码:
// hooks最后会替换为moment全局变量
// 扩展mement对象
hooks.fn = proto;
// 为moment添加静态方法
hooks.min = min;
hooks.max = max;
hooks.now = now;
hooks.utc = createUTC;
hooks.unix = createUnix;
hooks.months = listMonths;
hooks.isDate = isDate;
hooks.locale = getSetGlobalLocale;
hooks.invalid = createInvalid;
hooks.duration = createDuration;
hooks.isMoment = isMoment;
hooks.weekdays = listWeekdays;
hooks.parseZone = createInZone;
hooks.localeData = getLocale;
hooks.isDuration = isDuration;
hooks.monthsShort = listMonthsShort;
hooks.weekdaysMin = listWeekdaysMin;
hooks.defineLocale = defineLocale;
hooks.updateLocale = updateLocale;
# 查看所有支持的时区
hooks.locales = listLocales;
hooks.weekdaysShort = listWeekdaysShort;
hooks.normalizeUnits = normalizeUnits;
hooks.relativeTimeRounding = getSetRelativeTimeRounding;
hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
hooks.calendarFormat = getCalendarFormat;
// 扩展mement对象
hooks.prototype = proto;
// 扩展duration对象
createDuration.fn = Duration.prototype;
createDuration.invalid = createInvalid$1;