Date utils without dependencies.
https://www.npmjs.com/package/@gambar/date-utils
- JavaScript 100%
|
|
||
|---|---|---|
| .forgejo/workflows | ||
| docs | ||
| src | ||
| tests | ||
| .gitignore | ||
| bun.lock | ||
| bunfig.toml | ||
| jsconfig.json | ||
| LICENSE | ||
| package.json | ||
| README.md | ||
| rolldown.config.js | ||
@gambar/date-utils
A lightweight, immutable date utility library with zero dependencies. Every operation returns a new instance — no surprises, no mutation.
Table of Contents
Installation
npm install @gambar/date-utils
# or
bun add @gambar/date-utils
// ESM
import { DateHelper } from "@gambar/date-utils";
// CJS
const { DateHelper } = require("@gambar/date-utils");
Documentation
| File | Contents |
|---|---|
| Construction & Parsing | Creating instances, parsing strings, validity, primitive conversions |
| Formatting | Rendering dates as strings, built-in and custom format patterns |
| Arithmetic | Adding and subtracting time units, month-end clamping behaviour |
| Boundaries | Snapping to the start or end of a calendar unit |
| Comparison | Boolean predicates, ordering operators, granular equality |
| Difference | Computing the gap between two dates as a number or structured object |
Basic Usage
import { DateHelper } from "@gambar/date-utils";
// Parse any common format automatically
const d = new DateHelper("15.03.2024");
d.format("YYYY-MM-DD"); // "2024-03-15"
d.format("DD.MM"); // "15.03"
d.addMonths(2).format(); // "15.05.2024"
d.isBefore("2025-01-01"); // true
// Chain operations — every method returns a new instance
const nextQuarter = DateHelper.now()
.startOf("month")
.addMonths(3)
.format("YYYY-MM-DD");
Real-world Example
A booking API returns dates as YYYY-MM-DD; the UI displays them as DD.MM.YYYY.
import { DateHelper } from "@gambar/date-utils";
// dates arrive from the API in ISO format
const offers = [
{ name: "Sea View Suite", from: "2024-06-01", to: "2024-06-08" },
{ name: "Mountain Retreat", from: "2024-07-14", to: "2024-07-19" },
{ name: "City Break", from: "2024-09-05", to: "2024-09-07" },
];
offers.map(({ name, from, to }) => {
const checkIn = new DateHelper(from);
const checkOut = new DateHelper(to);
const nights = Math.round(checkIn.diff(checkOut, "days"));
return `${name}: ${checkIn.format("DD.MM")} – ${checkOut.format("DD.MM.YYYY")}, ${nights} nights`;
});
// [
// "Sea View Suite: 01.06 – 08.06.2024, 7 nights",
// "Mountain Retreat: 14.07 – 19.07.2024, 5 nights",
// "City Break: 05.09 – 07.09.2024, 2 nights",
// ]