wanmeiyizhan/utils/moment.js
2025-02-17 19:07:07 +08:00

82 lines
1.6 KiB
JavaScript

// src/utils/moment.js
class MyMoment {
constructor(date) {
this.date = date ? new Date(date) : new Date();
}
static create(date) {
return new MyMoment(date);
}
unix() {
return Math.floor(this.date.getTime() / 1000);
}
format(formatStr) {
const options = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
};
let formatted = new Intl.DateTimeFormat('en-US', options).format(this.date);
if (formatStr) {
formatted = formatStr
.replace('YYYY', this.date.getFullYear())
.replace('MM', String(this.date.getMonth() + 1).padStart(2, '0'))
.replace('DD', String(this.date.getDate()).padStart(2, '0'))
.replace('HH', String(this.date.getHours()).padStart(2, '0'))
.replace('mm', String(this.date.getMinutes()).padStart(2, '0'))
.replace('ss', String(this.date.getSeconds()).padStart(2, '0'));
}
return formatted;
}
set(date) {
this.date = new Date(date);
return this;
}
year() {
return this.date.getFullYear();
}
month() {
return this.date.getMonth() + 1;
}
dateOfMonth() {
return this.date.getDate();
}
hour() {
return this.date.getHours();
}
minute() {
return this.date.getMinutes();
}
second() {
return this.date.getSeconds();
}
isLeapYear() {
const year = this.year();
return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}
static now() {
return new MyMoment();
}
}
export default MyMoment;