@nestjstools/clock
Version:
A lightweight, test-friendly clock abstraction for NestJS apps enabling flexible time management via dependency injection
90 lines • 2.64 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CalendarDate = void 0;
class CalendarDate {
year;
month;
day;
constructor(year, month, day) {
if (!CalendarDate.isValidDate(year, month, day)) {
throw new Error('Invalid date');
}
this.year = year;
this.month = month;
this.day = day;
}
static fromString(dateString) {
if (!/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
throw new Error('Invalid date format');
}
const [year, month, day] = dateString.split('-').map(Number);
return new CalendarDate(year, month, day);
}
static today() {
return CalendarDate.fromDate(new Date());
}
static fromDate(date) {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return new CalendarDate(year, month, day);
}
static isValidDate(year, month, day) {
const d = new Date(year, month - 1, day);
return (d.getFullYear() === year &&
d.getMonth() === month - 1 &&
d.getDate() === day);
}
toString() {
const mm = String(this.month).padStart(2, '0');
const dd = String(this.day).padStart(2, '0');
return `${this.year}-${mm}-${dd}`;
}
getYear() {
return this.year;
}
getMonth() {
return this.month;
}
getDay() {
return this.day;
}
equals(other) {
return (this.year === other.year &&
this.month === other.month &&
this.day === other.day);
}
toDate() {
return new Date(this.year, this.month - 1, this.day);
}
addDays(days) {
if (days < 0) {
throw new Error('days must be a positive number');
}
const date = this.toDate();
date.setDate(date.getDate() + days);
return CalendarDate.fromDate(date);
}
subtractDays(days) {
if (days < 0) {
throw new Error('days must be a positive number');
}
const date = this.toDate();
date.setDate(date.getDate() - days);
return CalendarDate.fromDate(date);
}
isBefore(other) {
return this.toDate() < other.toDate();
}
isAfter(other) {
return this.toDate() > other.toDate();
}
isSameOrBefore(other) {
return this.isBefore(other) || this.equals(other);
}
isSameOrAfter(other) {
return this.isAfter(other) || this.equals(other);
}
}
exports.CalendarDate = CalendarDate;
//# sourceMappingURL=calendar-date.js.map