rwadurian/backend/services/authorization-service/src/domain/value-objects/month.vo.ts

65 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { DomainError } from '@/shared/exceptions'
export class Month {
constructor(public readonly value: string) {
if (!/^\d{4}-\d{2}$/.test(value)) {
throw new DomainError('月份格式错误应为YYYY-MM')
}
}
static current(): Month {
const now = new Date()
const year = now.getFullYear()
const month = String(now.getMonth() + 1).padStart(2, '0')
return new Month(`${year}-${month}`)
}
static create(value: string): Month {
return new Month(value)
}
static fromDate(date: Date): Month {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
return new Month(`${year}-${month}`)
}
next(): Month {
const [year, month] = this.value.split('-').map(Number)
const nextMonth = month === 12 ? 1 : month + 1
const nextYear = month === 12 ? year + 1 : year
return new Month(`${nextYear}-${String(nextMonth).padStart(2, '0')}`)
}
previous(): Month {
const [year, month] = this.value.split('-').map(Number)
const prevMonth = month === 1 ? 12 : month - 1
const prevYear = month === 1 ? year - 1 : year
return new Month(`${prevYear}-${String(prevMonth).padStart(2, '0')}`)
}
equals(other: Month): boolean {
return this.value === other.value
}
isAfter(other: Month): boolean {
return this.value > other.value
}
isBefore(other: Month): boolean {
return this.value < other.value
}
toString(): string {
return this.value
}
getYear(): number {
return parseInt(this.value.split('-')[0])
}
getMonth(): number {
return parseInt(this.value.split('-')[1])
}
}