105 lines
2.5 KiB
JavaScript
105 lines
2.5 KiB
JavaScript
// myMoment.js
|
|
class MyMoment {
|
|
constructor(date) {
|
|
this.date = date ? new Date(date) : new Date(); // 默认当前时间
|
|
}
|
|
|
|
// 格式化日期
|
|
format(formatStr) {
|
|
const date = this.date;
|
|
const map = {
|
|
'YYYY': date.getFullYear(),
|
|
'MM': String(date.getMonth() + 1).padStart(2, '0'),
|
|
'DD': String(date.getDate()).padStart(2, '0'),
|
|
'HH': String(date.getHours()).padStart(2, '0'),
|
|
'mm': String(date.getMinutes()).padStart(2, '0'),
|
|
'ss': String(date.getSeconds()).padStart(2, '0'),
|
|
'SSS': String(date.getMilliseconds()).padStart(3, '0'),
|
|
};
|
|
|
|
return formatStr.replace(/YYYY|MM|DD|HH|mm|ss|SSS/g, (match) => map[match]);
|
|
}
|
|
|
|
// 设置日期
|
|
set(unit, value) {
|
|
switch (unit) {
|
|
case 'year':
|
|
case 'years':
|
|
this.date.setFullYear(this.date.getFullYear() + value);
|
|
break;
|
|
case 'month':
|
|
case 'months':
|
|
this.date.setMonth(this.date.getMonth() + value);
|
|
break;
|
|
case 'day':
|
|
case 'days':
|
|
this.date.setDate(this.date.getDate() + value);
|
|
break;
|
|
case 'hour':
|
|
case 'hours':
|
|
this.date.setHours(this.date.getHours() + value);
|
|
break;
|
|
case 'minute':
|
|
case 'minutes':
|
|
this.date.setMinutes(this.date.getMinutes() + value);
|
|
break;
|
|
case 'second':
|
|
case 'seconds':
|
|
this.date.setSeconds(this.date.getSeconds() + value);
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
return this; // 允许链式调用
|
|
}
|
|
|
|
// 获取日期
|
|
get(unit) {
|
|
switch (unit) {
|
|
case 'year':
|
|
case 'years':
|
|
return this.date.getFullYear();
|
|
case 'month':
|
|
case 'months':
|
|
return this.date.getMonth();
|
|
case 'day':
|
|
case 'days':
|
|
return this.date.getDate();
|
|
case 'hour':
|
|
case 'hours':
|
|
return this.date.getHours();
|
|
case 'minute':
|
|
case 'minutes':
|
|
return this.date.getMinutes();
|
|
case 'second':
|
|
case 'seconds':
|
|
return this.date.getSeconds();
|
|
default:
|
|
return this.date;
|
|
}
|
|
}
|
|
|
|
// 获取当前时间戳
|
|
valueOf() {
|
|
return this.date.getTime();
|
|
}
|
|
|
|
// 静态方法,解析时间字符串
|
|
static parse(dateStr) {
|
|
return new MyMoment(dateStr);
|
|
}
|
|
|
|
// 静态方法,获取当前时间
|
|
static now() {
|
|
return new MyMoment();
|
|
}
|
|
|
|
// 静态方法,创建一个指定日期的实例
|
|
static create(date) {
|
|
return new MyMoment(date);
|
|
}
|
|
}
|
|
|
|
// 导出 MyMoment 类
|
|
module.exports = MyMoment;
|