Day.js

Language: JavaScript

Utility

Day.js was created to provide a lightweight alternative to Moment.js while maintaining a familiar API. Its modular architecture allows importing only the features you need, reducing bundle size significantly for web applications.

Day.js is a minimalist JavaScript library for parsing, validating, manipulating, and formatting dates. It provides a modern API similar to Moment.js but with a much smaller footprint.

Installation

npm: npm install dayjs
yarn: yarn add dayjs

Usage

Day.js offers simple functions for working with dates, including parsing, formatting, adding or subtracting time, comparing dates, and working with relative times or durations.

Getting current date and formatting

import dayjs from 'dayjs';
const now = dayjs();
console.log(now.format('YYYY-MM-DD HH:mm:ss'));

Gets the current date and formats it as a string.

Parsing a date string

const date = dayjs('2025-08-22');
console.log(date.format('MMMM D, YYYY'));

Parses a string into a Day.js object and formats it.

Adding and subtracting time

const future = dayjs().add(7, 'day').subtract(2, 'hour');
console.log(future.format());

Adds 7 days and subtracts 2 hours from the current date.

Comparing dates

const d1 = dayjs('2025-08-22');
const d2 = dayjs('2025-09-01');
console.log(d1.isBefore(d2)); // true
console.log(d1.isAfter(d2)); // false

Compares two dates to check if one is before or after the other.

Relative time

import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
const past = dayjs('2025-08-15');
console.log(past.fromNow());

Displays relative time from now, e.g., '7 days ago', using the relativeTime plugin.

Working with UTC

import utc from 'dayjs/plugin/utc';
dayjs.extend(utc);
const utcTime = dayjs.utc('2025-08-22 12:00');
console.log(utcTime.format());

Uses the UTC plugin to handle dates in Coordinated Universal Time.

Error Handling

Invalid Date: Ensure the input string is in a valid format or use `dayjs(string, format)` with the correct format specified.
Plugin not loaded: Extend Day.js with required plugins before using their functions, e.g., `dayjs.extend(plugin)`.

Best Practices

Use plugins only for features you need to minimize bundle size.

Prefer Day.js for modern JavaScript projects requiring small date libraries.

Use immutable objects to avoid unintended mutations.

Use ISO 8601 strings when possible for consistent parsing.

Combine with timezone plugins for handling different time zones.