js-date-helpers
v1.0.3
Published
A lightweight collection of JavaScript utility functions for formatting and manipulating dates.
Readme
js-date-helpers
A lightweight, zero-dependency collection of JavaScript utility functions for formatting and manipulating dates.
Table of Contents
Installation
npm
npm install js-date-helpersyarn
yarn add js-date-helperspnpm
pnpm add js-date-helpersQuick Start
import {
formatDate,
formatDateTime,
formatFriendly,
addMonths,
getAge,
timeAgo,
format,
} from "js-date-helpers";
// Format current date
console.log(formatDate()); // "2025-12-15"
// Format date with time
console.log(formatDateTime()); // "2025-12-15 14:30"
// Friendly format
console.log(formatFriendly()); // "Monday, Dec 15, 2025"
// Add months to a date
console.log(addMonths(new Date(), 2));
// Calculate age from DOB
console.log(getAge("1990-05-15")); // age in years
// Relative time
console.log(timeAgo(new Date(Date.now() - 3600000))); // "1 hour ago"API Reference
Formatting Functions
formatDate(date?)
Format a date as YYYY-MM-DD.
Parameters:
date(Date, optional): Date to format. Defaults to current date.
Returns: String in YYYY-MM-DD format
Example:
import { formatDate } from "js-date-helpers";
formatDate(); // "2025-12-15"
formatDate(new Date("2025-08-25")); // "2025-08-25"formatDateTime(date?)
Format a date with time as YYYY-MM-DD HH:mm.
Parameters:
date(Date, optional): Date to format. Defaults to current date.
Returns: String in YYYY-MM-DD HH:mm format
Example:
import { formatDateTime } from "js-date-helpers";
formatDateTime(); // "2025-12-15 14:30"
formatDateTime(new Date("2025-08-25T13:45:00")); // "2025-08-25 13:45"formatFriendly(date?)
Format a date in a human-readable format (e.g., Monday, Aug 25, 2025).
Parameters:
date(Date, optional): Date to format. Defaults to current date.
Returns: String in friendly format
Example:
import { formatFriendly } from "js-date-helpers";
formatFriendly(); // "Monday, Dec 15, 2025"
formatFriendly(new Date("2025-08-25")); // "Monday, Aug 25, 2025"format(input?, mask?, options?)
Advanced date formatting with custom masks and locale support.
Parameters:
input(Date | number | string, optional): Date to format. Accepts anythingnew Date()accepts. Defaults to current date.mask(string, optional): Format string. Defaults to"YYYY-MM-DD".options(object, optional):locale(Locale): Custom locale for formattingutc(boolean): Use UTC timezone. Defaults tofalse.
Returns: Formatted date string
Format Tokens:
| Token | Description | Example |
| ----------- | ------------------------------- | -------------------- |
| YYYY | 4-digit year | 2025 |
| YY | 2-digit year | 25 |
| GGGG | ISO week-year | 2025 |
| M | Month without padding | 1-12 |
| MM | Month with padding | 01-12 |
| MMM | Short month name | Jan, Feb... |
| MMMM | Full month name | January, February... |
| D | Day without padding | 1-31 |
| DD | Day with padding | 01-31 |
| Do | Ordinal day | 1st, 2nd, 3rd... |
| ddd | Short weekday | Mon, Tue... |
| dddd | Full weekday | Monday, Tuesday... |
| DDD | Day of year without padding | 1-366 |
| DDDD | Day of year with padding | 001-366 |
| H | Hour (24h) without padding | 0-23 |
| HH | Hour (24h) with padding | 00-23 |
| h | Hour (12h) without padding | 1-12 |
| hh | Hour (12h) with padding | 01-12 |
| m | Minute without padding | 0-59 |
| mm | Minute with padding | 00-59 |
| s | Second without padding | 0-59 |
| ss | Second with padding | 00-59 |
| S | Millisecond (1 digit) | 0-9 |
| SS | Millisecond (2 digits) | 00-99 |
| SSS | Millisecond (3 digits) | 000-999 |
| A | Meridiem (uppercase) | AM, PM |
| a | Meridiem (lowercase) | am, pm |
| Q | Quarter without padding | 1-4 |
| Qo | Quarter ordinal | 1st, 2nd, 3rd, 4th |
| W | ISO week number without padding | 1-53 |
| WW | ISO week number with padding | 01-53 |
| E | ISO weekday | 1-7 (Mon-Sun) |
| Z | Timezone offset | +05:45, -08:00 |
| ZZ | Timezone offset (no colon) | +0545, -0800 |
| X | Unix timestamp (seconds) | 1756091106 |
| x | Unix timestamp (milliseconds) | 1756091106123 |
| [literal] | Escape literal characters | [UTC] → UTC |
Example:
import { format } from "js-date-helpers";
const d = new Date("2025-08-25T13:45:06.123");
format(d, "YYYY-MM-DD"); // "2025-08-25"
format(d, "ddd, MMM D, YYYY"); // "Mon, Aug 25, 2025"
format(d, "YYYY-[W]WW-E"); // "2025-W35-1"
format(d, "hh:mm A"); // "01:45 PM"
format(d, "HH:mm:ss.SSS"); // "13:45:06.123"
format(d, "Qo [quarter], DDDD [DoY]"); // "3rd quarter, 237 DoY"
format(d, "Z / ZZ"); // "+05:45 / +0545" (depends on timezone)
format(d, "X (x)"); // "1756091106 (1756091106123)"Date Manipulation Functions
addMonths(date?, months?)
Add or subtract months from a date.
Parameters:
date(Date, optional): Base date. Defaults to current date.months(number, optional): Number of months to add. Defaults to 0.
Returns: New Date object
Example:
import { addMonths } from "js-date-helpers";
addMonths(new Date("2025-08-15"), 2); // Oct 15, 2025
addMonths(new Date("2025-08-15"), -3); // May 15, 2025addYears(date?, years?)
Add or subtract years from a date.
Parameters:
date(Date, optional): Base date. Defaults to current date.years(number, optional): Number of years to add. Defaults to 0.
Returns: New Date object
Example:
import { addYears } from "js-date-helpers";
addYears(new Date("2025-08-15"), 5); // Aug 15, 2030
addYears(new Date("2025-08-15"), -1); // Aug 15, 2024startOfMonth(date?)
Get the first day of the month.
Parameters:
date(Date, optional): Date to get month from. Defaults to current date.
Returns: Date object representing the first day of the month
Example:
import { startOfMonth } from "js-date-helpers";
startOfMonth(new Date("2025-08-25")); // Aug 1, 2025endOfMonth(date?)
Get the last day of the month.
Parameters:
date(Date, optional): Date to get month from. Defaults to current date.
Returns: Date object representing the last day of the month
Example:
import { endOfMonth } from "js-date-helpers";
endOfMonth(new Date("2025-08-25")); // Aug 31, 2025Date Comparison Functions
isSameDay(date1, date2)
Check if two dates fall on the same calendar day.
Parameters:
date1(Date): First datedate2(Date): Second date
Returns: Boolean
Example:
import { isSameDay } from "js-date-helpers";
isSameDay(new Date("2025-08-25T10:00:00"), new Date("2025-08-25T14:30:00")); // true
isSameDay(new Date("2025-08-25"), new Date("2025-08-26")); // falseisSameMonth(date1, date2)
Check if two dates fall in the same month and year.
Parameters:
date1(Date): First datedate2(Date): Second date
Returns: Boolean
Example:
import { isSameMonth } from "js-date-helpers";
isSameMonth(new Date("2025-08-25"), new Date("2025-08-15")); // true
isSameMonth(new Date("2025-08-25"), new Date("2025-09-25")); // falseDate Information Functions
daysInMonth(date?)
Get the number of days in a month.
Parameters:
date(Date, optional): Date to get month from. Defaults to current date.
Returns: Number of days (28-31)
Example:
import { daysInMonth } from "js-date-helpers";
daysInMonth(new Date("2025-02-15")); // 28
daysInMonth(new Date("2025-08-15")); // 31getAge(dob)
Calculate age in years from a date of birth.
Parameters:
dob(Date | string): Date of birth (accepts any format thatnew Date()accepts)
Returns: Age in years (number)
Example:
import { getAge } from "js-date-helpers";
getAge("1990-05-15"); // 35 (as of Dec 2025)
getAge(new Date("1990-05-15")); // 35getWeekNumber(date?)
Get the ISO week number (1-53) of a date.
Parameters:
date(Date, optional): Date to get week from. Defaults to current date.
Returns: Week number (1-53)
Example:
import { getWeekNumber } from "js-date-helpers";
getWeekNumber(new Date("2025-08-25")); // 35
getWeekNumber(new Date("2025-01-01")); // 1getQuarter(date?)
Get the quarter of the year (1-4).
Parameters:
date(Date, optional): Date to get quarter from. Defaults to current date.
Returns: Quarter number (1-4)
Example:
import { getQuarter } from "js-date-helpers";
getQuarter(new Date("2025-08-25")); // 3
getQuarter(new Date("2025-01-15")); // 1
getQuarter(new Date("2025-10-15")); // 4Utility Functions
timeAgo(date)
Get a human-readable relative time string (e.g., "2 days ago").
Parameters:
date(Date | string | number): Reference date (accepts any format thatnew Date()accepts)
Returns: Relative time string
Example:
import { timeAgo } from "js-date-helpers";
// Assuming current time is Dec 15, 2025, 14:30
timeAgo(new Date(Date.now() - 30000)); // "just now"
timeAgo(new Date(Date.now() - 120000)); // "2 minutes ago"
timeAgo(new Date(Date.now() - 3600000)); // "1 hour ago"
timeAgo(new Date(Date.now() - 86400000)); // "1 day ago"
timeAgo(new Date(Date.now() - 604800000)); // "1 week ago"
timeAgo(new Date(Date.now() - 2592000000)); // "1 month ago"
timeAgo(new Date(Date.now() - 31536000000)); // "1 year ago"toISODate(date?)
Convert a date to ISO string format, normalized to UTC.
Parameters:
date(Date, optional): Date to convert. Defaults to current date.
Returns: ISO string (UTC normalized)
Example:
import { toISODate } from "js-date-helpers";
toISODate(new Date("2025-08-25T13:45:06.123"));
// "2025-08-25T13:45:06.123Z"Advanced Usage
Custom Format Masks
You can create complex date formats using the format() function with any combination of tokens:
import { format } from "js-date-helpers";
const date = new Date("2025-12-15T14:30:45");
// Business format
format(date, "DD/MM/YYYY"); // "15/12/2025"
// ISO week format
format(date, "GGGG-[W]WW-E"); // "2025-W50-1"
// Log format with timestamp
format(date, "YYYY-MM-DD HH:mm:ss.SSS"); // "2025-12-15 14:30:45.000"
// Filename safe format
format(date, "YYYY_MM_DD__HH-mm-ss"); // "2025_12_15__14-30-45"
// With escaped literals
format(date, "[Date:] YYYY-MM-DD [at] HH:mm [UTC]Z");
// "Date: 2025-12-15 at 14:30 UTC+05:45"Locale Support
The format() function supports custom locales. Here's how to use it:
import { format } from "js-date-helpers";
const customLocale = {
months: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
],
monthsShort: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
],
weekdays: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
],
weekdaysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
meridiem: (h, m, isLower) => (isLower ? "am" : "AM"),
ordinal: (n) => {
const suffix =
["st", "nd", "rd"][((((n + 90) % 100) - 10) % 10) - 1] || "th";
return n + suffix;
},
};
const date = new Date("2025-08-25T13:45:00");
format(date, "dddd, MMMM Do, YYYY [at] hh:mm A", { locale: customLocale });
// "Monday, August 25th, 2025 at 01:45 PM"Examples
Common Use Cases
import {
formatDate,
formatDateTime,
addMonths,
getAge,
timeAgo,
format,
} from "js-date-helpers";
// Date validation for forms
const userBirthDate = "1990-05-15";
const age = getAge(userBirthDate);
console.log(`Age: ${age} years old`);
// Event scheduling
const eventDate = new Date("2025-12-25");
console.log(`Event is ${timeAgo(eventDate)}`);
// Database storage
const now = new Date();
const dateForDB = formatDate(now);
const dateTimeForDB = formatDateTime(now);
// Display in UI
const displayDate = format(now, "dddd, MMMM D, YYYY");
const displayTime = format(now, "hh:mm A");
// Adding duration to dates
const meetingDate = new Date("2025-12-25");
const followUpDate = addMonths(meetingDate, 1);
console.log(`Follow-up meeting: ${formatDate(followUpDate)}`);
// Checking date ranges
const startDate = new Date("2025-08-01");
const endDate = new Date("2025-08-31");
const checkDate = new Date("2025-08-15");
if (checkDate >= startDate && checkDate <= endDate) {
console.log("Date is within range");
}Features
✨ Zero Dependencies - No external packages required
📦 Lightweight - Minimal bundle size
🎯 Simple API - Intuitive function names and parameters
🌍 Locale Support - Format dates in any language
⏱️ Timezone Aware - Handle UTC and local timezones
📅 Comprehensive - 15+ utility functions for all date needs
✅ Well-Tested - Reliable date handling
Browser Support
| Browser | Support | | ------- | -------------------- | | Chrome | ✅ Latest | | Firefox | ✅ Latest | | Safari | ✅ Latest | | Edge | ✅ Latest | | IE 11 | ⚠️ Requires Polyfill |
Contributing
Contributions are welcome! Please feel free to submit a pull request or open an issue for bugs and feature requests.
Authors:
- Sushan
- Niroj
- Bhupendra
- Nikhil
License
This project is licensed under the ISC License - see the LICENSE file for details.
Support
For npm package information, visit npm.
