date-manip
Version:
A lightweight JavaScript date utility library that provides modularity, high performance, and additional features. It supports various date operations, including date addition and subtraction, formatting, comparison, etc.
74 lines (73 loc) • 1.62 kB
JavaScript
import * as fns from "date-manip";
export * from "date-manip";
const { parse, get, set } = fns;
class DateChain {
constructor(input, format) {
const _input = input instanceof DateChain ? input._d : input;
this._i = input;
this._f = format;
this._d = parse(_input, format);
}
clone() {
return new DateChain(this, this._f);
}
toArray() {
const date = this._d;
return [
get(date, "year"),
get(date, "month"),
get(date, "date"),
get(date, "hours"),
get(date, "minutes"),
get(date, "seconds"),
get(date, "milliseconds")
// -date.getTimezoneOffset()
];
}
toDate() {
return new Date(this._d);
}
toISOString() {
return this._d.toISOString();
}
toJSON() {
return this.toISOString();
}
toString() {
return this._d.toString();
}
valueOf() {
return this._d.valueOf();
}
}
const proto = DateChain.prototype;
Object.entries(fns.units).forEach(([, method]) => {
const fn = function(val) {
if (val == null) {
return get(this._d, method);
}
set(this._d, method, val);
return this;
};
proto[method] = fn;
if (method !== "time") {
proto[`${method}s`] = fn;
}
});
const exclude = ["compile", "parse", "units"];
Object.entries(fns).forEach(([name, method]) => {
if (!exclude.includes(name)) {
proto[name] = function() {
const date = this._d;
const ret = method(date, ...arguments);
return ret === date ? this : ret;
};
}
DateChain[name] = method;
});
function chain(input, format) {
return new DateChain(input, format);
}
export {
chain
};