Home » Day.js Tutorial with Examples

Day.js Tutorial with Examples

Day.js is a minimalist JavaScript library for working with dates. It is often compared to Moment.js due to its similar API but is significantly smaller in size.

Day.js makes it simple to parse, validate, manipulate, and format dates without compromising on performance or size.

In this tutorial, we will cover:

  1. What is Day.js?
  2. Installation and Setup
  3. Creating and Formatting Dates
  4. Manipulating Dates (Add, Subtract, etc.)
  5. Parsing Dates
  6. Comparing Dates
  7. Working with Time Zones
  8. Displaying Relative Time
  9. Examples and Use Cases

Let’s dive into each section with examples.

1. What is Day.js?

Day.js is a lightweight, immutable date library that enables you to work with dates in JavaScript.

It provides a Moment.js-like API, making it simple to pick up if you’ve worked with other date libraries, but without the large bundle size.

2. Installation and Setup

You can install Day.js via npm, yarn, or use it via CDN in the browser.

Installation with npm:

npm install dayjs

Installation with yarn:

yarn add dayjs

Including Day.js via CDN:

<script src="https://unpkg.com/dayjs"></script>

Importing Day.js into your project:

const dayjs = require('dayjs');

// ES6 Import
import dayjs from 'dayjs';

3. Creating and Formatting Dates

Example 1: Creating the Current Date

You can create the current date using dayjs().

const dayjs = require('dayjs');

// Creating the current date
const now = dayjs();
console.log(now.format());  // Output: Current date and time in ISO format

Example 2: Formatting Dates

Day.js provides the format() method to format dates.

const formattedDate = dayjs().format('YYYY-MM-DD');
console.log(formattedDate);  // Output: e.g., "2024-10-17"

You can format the date using custom tokens:

  • YYYY: Year (4 digits)
  • MM: Month (2 digits)
  • DD: Day of the month
  • HH: Hour (24-hour format)
  • mm: Minute
  • ss: Second

Example 3: Creating Specific Dates

You can create specific dates by passing arguments to the dayjs() constructor.

// Creating a specific date (October 15, 2023)
const specificDate = dayjs('2023-10-15');
console.log(specificDate.format('MMMM D, YYYY'));  // Output: "October 15, 2023"

4. Manipulating Dates (Add, Subtract, etc.)

Day.js makes it easy to add or subtract time from a date.

Example 1: Adding Time to a Date

// Add 5 days to the current date
const futureDate = dayjs().add(5, 'day');
console.log(futureDate.format('YYYY-MM-DD'));  // Output: Date 5 days from now

Example 2: Subtracting Time from a Date

// Subtract 2 months from the current date
const pastDate = dayjs().subtract(2, 'month');
console.log(pastDate.format('YYYY-MM-DD'));  // Output: Date 2 months ago

Example 3: Chaining Date Manipulations

You can chain multiple manipulations together.

const manipulatedDate = dayjs().add(1, 'week').subtract(3, 'days');
console.log(manipulatedDate.format('YYYY-MM-DD'));  // Output: 1 week ahead, minus 3 days

5. Parsing Dates

Day.js can parse dates from strings in different formats.

Example 1: Parsing Dates from Strings

// Parsing a date string
const parsedDate = dayjs('2024-10-17', 'YYYY-MM-DD');
console.log(parsedDate.format('MMMM D, YYYY'));  // Output: "October 17, 2024"

Example 2: Parsing Dates with Time

const parsedDateTime = dayjs('2024-10-17 14:30:00', 'YYYY-MM-DD HH:mm:ss');
console.log(parsedDateTime.format('MMMM D, YYYY h:mm A'));  // Output: "October 17, 2024 2:30 PM"

6. Comparing Dates

Day.js provides several methods to compare dates.

Example 1: Checking if a Date is Before or After Another

const date1 = dayjs('2024-10-01');
const date2 = dayjs('2024-10-17');

console.log(date1.isBefore(date2));  // Output: true
console.log(date2.isAfter(date1));   // Output: true

Example 2: Checking if Two Dates Are the Same

const date1 = dayjs('2024-10-17');
const date2 = dayjs('2024-10-17');

console.log(date1.isSame(date2));  // Output: true

Example 3: Checking if a Date is Between Two Dates

const startDate = dayjs('2024-10-01');
const endDate = dayjs('2024-10-31');
const checkDate = dayjs('2024-10-15');

console.log(checkDate.isBetween(startDate, endDate));  // Output: true

7. Working with Time Zones

Day.js requires the dayjs/plugin/utc and dayjs/plugin/timezone plugins to work with time zones.

Example: Using Time Zones with Day.js

Step 1: Install the required plugin:

npm install dayjs-plugin-utc
npm install dayjs-plugin-timezone

Step 2: Use time zone plugins

const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');

dayjs.extend(utc);
dayjs.extend(timezone);

// Set a time zone
const newYorkTime = dayjs().tz('America/New_York').format('MMMM D, YYYY h:mm A');
console.log('New York Time:', newYorkTime);

const tokyoTime = dayjs().tz('Asia/Tokyo').format('MMMM D, YYYY h:mm A');
console.log('Tokyo Time:', tokyoTime);

In this example:

  • We use the timezone() plugin to work with different time zones and convert the current time to New York and Tokyo time.

8. Displaying Relative Time

To display relative time (e.g., “3 days ago” or “in 2 hours”), you need the relativeTime plugin.

Example: Displaying Relative Time

Step 1: Install the plugin:

npm install dayjs-plugin-relative-time

Step 2: Using the relative time plugin:

const dayjs = require('dayjs');
const relativeTime = require('dayjs/plugin/relativeTime');

dayjs.extend(relativeTime);

// Example relative times
const pastDate = dayjs().subtract(3, 'days');
console.log(pastDate.fromNow());  // Output: "3 days ago"

const futureDate = dayjs().add(5, 'hours');
console.log(futureDate.fromNow());  // Output: "in 5 hours"

9. Examples and Use Cases

Example 1: Countdown to a Future Date

You can use Day.js to create countdowns to specific events.

const eventDate = dayjs('2024-12-25');
const now = dayjs();
const daysUntilEvent = eventDate.diff(now, 'days');
console.log(`Days until Christmas 2024: ${daysUntilEvent}`);

Example 2: Displaying Days Since a Specific Event

You can calculate the time that has passed since a particular date.

const startDate = dayjs('2023-01-01');
const now = dayjs();
const daysSinceStart = now.diff(startDate, 'days');
console.log(`Days since the start of 2023: ${daysSinceStart}`);

Example 3: Formatting Dates for Different Locales

Day.js supports various locales for formatting dates.

const dayjs = require('dayjs');
const localeData = require('dayjs/plugin/localeData');

dayjs.extend(localeData);
dayjs.locale('fr');

console.log(dayjs().format('LLLL'));  // Output date in French locale format

Summary of Day.js Key Methods

Method Description
dayjs() Creates a new Day.js object for the current date/time.
format() Formats the date according to the provided string tokens.
add() Adds time to the date object (e.g., days, months).
subtract() Subtracts time from the date object.
isBefore() Checks if one date is before another.
isAfter() Checks if one date is after another.
isSame() Checks if two dates are the same.
diff() Calculates the difference between two dates.
fromNow() Displays relative time (e.g., “5 minutes ago”).
tz() Converts time to a specific time zone (with plugin).

Conclusion

Day.js is an excellent lightweight alternative to larger date libraries like Moment.js, providing similar functionality with a much smaller footprint.

In this tutorial, we covered:

  • Creating and formatting dates with Day.js.
  • Manipulating dates by adding or subtracting time.
  • Parsing dates from strings and working with time zones.
  • Comparing dates and displaying relative time.

You may also like