dayjs-plugin-time-interval
Version:
A Dayjs plugin to add support for time intervals
74 lines (73 loc) • 2.22 kB
JavaScript
// src/index.ts
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
var plugin = (_options, _dayjsClass, dayjsFactory) => {
if (!dayjsFactory.duration) {
dayjsFactory.extend(duration);
}
dayjsFactory.timeInterval = function(config) {
if (typeof config === "string") {
const [start, end] = config.split("/");
return new TimeInterval(dayjs(start), dayjs(end));
}
return new TimeInterval(
"start" in config ? dayjs(config.start) : dayjs(config.end).add(
dayjs.isDuration(config.duration) ? config.duration : dayjs.duration(config.duration)
),
"end" in config ? dayjs(config.end) : dayjs(config.start).add(
dayjs.isDuration(config.duration) ? config.duration : dayjs.duration(config.duration)
)
);
};
dayjsFactory.isTimeInterval = function(t) {
return t instanceof TimeInterval;
};
};
var index_default = plugin;
var TimeInterval = class _TimeInterval {
constructor(start, end) {
this.start = start;
this.end = end;
}
get duration() {
return dayjs.duration(this.end.diff(this.start));
}
clone() {
return new _TimeInterval(this.start, this.end);
}
isValid(unit) {
return this.start.isBefore(this.end, unit);
}
isSame(other, unit) {
return this.start.isSame(other.start, unit) && this.end.isSame(other.end, unit);
}
overlaps(other, unit) {
return this.start.isBefore(other.end, unit) && other.start.isBefore(this.end, unit);
}
includes(d, unit) {
return this.end.isAfter(d, unit) && (this.start.isBefore(d, unit) || this.start.isSame(d, unit));
}
withStart(start) {
const newStart = typeof start === "function" ? start(this.start) : start;
return new _TimeInterval(dayjs(newStart), this.end);
}
withEnd(end) {
const newEnd = typeof end === "function" ? end(this.end) : end;
return new _TimeInterval(this.start, dayjs(newEnd));
}
toJSON() {
return this.toISOString();
}
toISOString() {
return `${this.start.toISOString()}/${this.end.toISOString()}`;
}
format(formatStr) {
return {
start: this.start.format(formatStr),
end: this.end.format(formatStr)
};
}
};
export {
index_default as default
};