NODE HELP

Day.js npm (How It Works For Developers)

Published September 29, 2024
Share:

Handling dates and times in JavaScript has historically been a challenging task due to the limitations and quirks of the built-in Date object. While the native Date object provides basic functionality, it often falls short in terms of usability, leading developers to seek out more robust solutions. One such solution is Day.js, a minimalist JavaScript library for parsing, validating, manipulating, and displaying dates and times.

This article explores the features, benefits, and usage of Day.js, demonstrating why it has become a popular choice among devs.

What is Day.js?

Day.js is a lightweight JavaScript library that provides a simple API for working with dates and times to display the date and time correctly in modern browsers. It was designed to be an alternative to the same modern API Moment.js, a widely used but much heavier library. Day.js is only 2kB in size (gzipped), making it an excellent choice for performance-conscious applications. Despite its small footprint, the Day.js library is an alternative to Moment.js and offers powerful features that cover the most common use cases.

Day.js npm (How It Works For Developers): Figure 1 - Day.js

Key Features

Here are some key features of the Day.js library:

  1. Lightweight: With its tiny size and advanced formatting options, Day.js ensures that your application remains fast and efficient.
  2. Immutable: Day.js objects are immutable, meaning that methods do not mutate the original object, but instead return new instances.
  3. Chainable API: Methods in Day.js can be chained together, making code more readable and concise.
  4. Internationalization: Day.js supports multiple locales, allowing for easy localization of dates and times.
  5. Plugin System: A modular plugin system allows you to extend Day.js functionality without bloating the core library.
  6. Compatibility: Day.js is designed to be API-compatible with Moment.js, making it easy to migrate existing codebases.

Installation

Day.js can be easily installed via npm or yarn. It can also be included directly in your HTML file using a CDN.

Using npm

npm install dayjs
npm install dayjs
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install dayjs
VB   C#

Basic Usage

Day.js offers extensive support for time zones, enabling developers to effortlessly manage local time and perform time manipulation tasks with precision. With its strict parsing capabilities, Day.js ensures accurate interpretation of date and time values, allowing for reliable and consistent results. Whether it's subtracting time or updating values, Day.js makes it easy to work with dates and times, providing additional features like creating new instances for enhanced flexibility.

Let's look into some examples of working with Day.js.

1. Creating Dates

Creating a new date instance in Day.js is straightforward. The following example demonstrates it:

const dayjs = require('dayjs');
// Current date and time
const now = dayjs();
// Specific date and time
const specificDate = dayjs('2023-05-25');
const dayjs = require('dayjs');
// Current date and time
const now = dayjs();
// Specific date and time
const specificDate = dayjs('2023-05-25');
const dayjs = require( 'dayjs');
' Current date and time
const now = dayjs()
' Specific date and time
const specificDate = dayjs( '2023-05-25');
VB   C#

2. Formatting Dates

Day.js provides a new instance flexible and powerful way to format dates:

const date = dayjs('2023-05-25');
console.log(date.format('YYYY-MM-DD')); // 2023-05-25
console.log(date.format('dddd, MMMM D, YYYY')); // Thursday, May 25, 2023
const date = dayjs('2023-05-25');
console.log(date.format('YYYY-MM-DD')); // 2023-05-25
console.log(date.format('dddd, MMMM D, YYYY')); // Thursday, May 25, 2023
const [date] = dayjs( '2023-05-25');
console.log([date].format( 'YYYY-MM-DD')); ' 2023-05-25
console.log([date].format( 'dddd, MMMM D, YYYY')); ' Thursday, May 25, 2023
VB   C#

3. Parsing Dates

Day.js can parse date objects from strings and displays dates in various formats:

const date1 = dayjs('2023-05-25');
const date2 = dayjs('05/25/2023', 'MM/DD/YYYY');
console.log(date1.isSame(date2)); // true
const date1 = dayjs('2023-05-25');
const date2 = dayjs('05/25/2023', 'MM/DD/YYYY');
console.log(date1.isSame(date2)); // true
const date1 = dayjs( '2023-05-25');
const date2 = dayjs( '05/25/2023', 'MM/DD/YYYY');
console.log(date1.isSame(date2)) ' true
VB   C#

4. Manipulating Dates

Day.js allows for easy manipulation of dates with its chainable API:

const date = dayjs('2023-05-25');
const nextWeek = date.add(1, 'week'); // Updated Value
const lastMonth = date.subtract(1, 'month'); // Updated Value
console.log(nextWeek.format('YYYY-MM-DD')); // 2023-06-01
console.log(lastMonth.format('YYYY-MM-DD')); // 2023-04-25
const date = dayjs('2023-05-25');
const nextWeek = date.add(1, 'week'); // Updated Value
const lastMonth = date.subtract(1, 'month'); // Updated Value
console.log(nextWeek.format('YYYY-MM-DD')); // 2023-06-01
console.log(lastMonth.format('YYYY-MM-DD')); // 2023-04-25
const [date] = dayjs( '2023-05-25');
const nextWeek = [date].add(1, 'week'); ' Updated Value
const lastMonth = [date].subtract(1, 'month'); ' Updated Value
console.log(nextWeek.format( 'YYYY-MM-DD')); ' 2023-06-01
console.log(lastMonth.format( 'YYYY-MM-DD')); ' 2023-04-25
VB   C#

5. Comparing Dates

Comparing dates in Day.js is simple and intuitive:

const date1 = dayjs('2023-05-25');
const date2 = dayjs('2023-06-01');
console.log(date1.isBefore(date2)); // true
console.log(date1.isAfter(date2)); // false
console.log(date1.isSame(date2)); // false
const date1 = dayjs('2023-05-25');
const date2 = dayjs('2023-06-01');
console.log(date1.isBefore(date2)); // true
console.log(date1.isAfter(date2)); // false
console.log(date1.isSame(date2)); // false
const date1 = dayjs( '2023-05-25');
const date2 = dayjs( '2023-06-01');
console.log(date1.isBefore(date2)) ' true
console.log(date1.isAfter(date2)) ' false
console.log(date1.isSame(date2)) ' false
VB   C#

6. Localization

Day.js supports internationalization (i18n) for working with different locales:

const dayjs = require('dayjs');
const localizedFormat = require('dayjs/plugin/localizedFormat');
const localeData = require('dayjs/plugin/localeData');
const updateLocale = require('dayjs/plugin/updateLocale');
dayjs.extend(localizedFormat);
dayjs.extend(localeData);
dayjs.extend(updateLocale);
dayjs.locale('fr');
console.log(dayjs().format('dddd, MMMM D, YYYY')); // jeudi, mai 25, 2023
dayjs.updateLocale('fr', {
    months: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
    weekdays: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi']
});
console.log(dayjs().format('dddd, MMMM D, YYYY')); // jeudi, mai 25, 2023
const dayjs = require('dayjs');
const localizedFormat = require('dayjs/plugin/localizedFormat');
const localeData = require('dayjs/plugin/localeData');
const updateLocale = require('dayjs/plugin/updateLocale');
dayjs.extend(localizedFormat);
dayjs.extend(localeData);
dayjs.extend(updateLocale);
dayjs.locale('fr');
console.log(dayjs().format('dddd, MMMM D, YYYY')); // jeudi, mai 25, 2023
dayjs.updateLocale('fr', {
    months: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
    weekdays: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi']
});
console.log(dayjs().format('dddd, MMMM D, YYYY')); // jeudi, mai 25, 2023
const dayjs = require( 'dayjs');
const localizedFormat = require( 'dayjs/plugin/localizedFormat');
const localeData = require( 'dayjs/plugin/localeData');
const updateLocale = require( 'dayjs/plugin/updateLocale');
dayjs.extend(localizedFormat)
dayjs.extend(localeData)
dayjs.extend(updateLocale)
dayjs.locale( 'fr');
console.log(dayjs().format( 'dddd, MMMM D, YYYY')); ' jeudi, mai 25, 2023
dayjs.updateLocale( 'fr', { months: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'], weekdays: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'] });
console.log(dayjs().format( 'dddd, MMMM D, YYYY')); ' jeudi, mai 25, 2023
VB   C#

Using Day.js with IronPDF to Add Dates to PDFs in Node.js

Combining the power of Day.js, a lightweight JavaScript date library package, with IronPDF, a versatile PDF generation and manipulation library for Node.js, allows developers to efficiently handle dates in their PDF documents.

IronPDF - The Node.js PDF Library

IronPDF for Node.js is a comprehensive library that empowers developers to create, manipulate, and interact with PDF documents seamlessly within their Node.js applications. Offering a rich set of features, IronPDF simplifies tasks such as generating PDFs from HTML, website URLs, or existing documents, adding text, images, and interactive elements, as well as converting HTML to PDF with precision.

Day.js npm (How It Works For Developers): Figure 2 - IronPDF

For more detailed information on IronPDF for Node.js, please visit this documentation page.

Getting Started

First, ensure you have the necessary packages installed. You can install Day.js and IronPDF via npm:

npm i @ironsoftware/ironpdf
npm i @ironsoftware/ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm i @ironsoftware/ironpdf
VB   C#

Adding Digital Signatures with Dates

IronPDF also supports adding digital signatures to PDFs. Here’s how to add a signature with a timestamp using Day.js.

import dayjs from 'dayjs';
import { PdfDocument } from "@ironsoftware/ironpdf";
(async () => {
    // Import a PDF
    const pdf = await PdfDocument.open("sample.pdf");
    // Get the current date and time for the signature
    const signatureDate = dayjs().toDate();
    // Sign the PDF with a digital certificate
    await pdf.signDigitalSignature({
        certificatePath: "IronSoftware.pfx",
        certificatePassword: "123456",
        signingReason: "To show how to sign a PDF",
        signingLocation: "Chicago, USA",
        signatureDate: signatureDate,
        signatureImage: {
            SignatureImagePath: "logo.png"
        }
    });
    // Save the signed PDF
    await pdf.saveAs("signed_with_date.pdf");
})();
import dayjs from 'dayjs';
import { PdfDocument } from "@ironsoftware/ironpdf";
(async () => {
    // Import a PDF
    const pdf = await PdfDocument.open("sample.pdf");
    // Get the current date and time for the signature
    const signatureDate = dayjs().toDate();
    // Sign the PDF with a digital certificate
    await pdf.signDigitalSignature({
        certificatePath: "IronSoftware.pfx",
        certificatePassword: "123456",
        signingReason: "To show how to sign a PDF",
        signingLocation: "Chicago, USA",
        signatureDate: signatureDate,
        signatureImage: {
            SignatureImagePath: "logo.png"
        }
    });
    // Save the signed PDF
    await pdf.saveAs("signed_with_date.pdf");
})();
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import dayjs from 'dayjs'; import { PdfDocument } from "@ironsoftware/ironpdf"; (async() => { const pdf = await PdfDocument.open("sample.pdf"); const signatureDate = dayjs().toDate(); await pdf.signDigitalSignature({ certificatePath: "IronSoftware.pfx", certificatePassword: "123456", signingReason: "To show how to sign a PDF", signingLocation: "Chicago, USA", signatureDate: signatureDate, signatureImage: { SignatureImagePath: "logo.png" } }); await pdf.saveAs("signed_with_date.pdf"); })();
VB   C#

Here is the output:

Day.js npm (How It Works For Developers): Figure 3 - PDF Output

You can also use ready-to-use code examples to immediately get started with the library in your Node.js application. For further exploring you can also visit this API Reference page.

Conclusion

Day.js is a powerful and efficient library for managing dates and times in JavaScript. Its lightweight nature, support for immutable data structures, and compatibility with Moment.js make it an attractive choice for developers looking to handle date and time operations without adding significant overhead to their applications.

By integrating Day.js with IronPDF, developers can easily handle dates in their PDF documents. Whether generating PDFs from URLs or HTML strings or adding digital signatures with timestamps, Day.js provides a simple and powerful way to manage dates. This combination enhances the functionality of your Node.js applications, allowing for robust and dynamic PDF document management.

Experience IronPDF's starting at $749. See for yourself how powerful PDF generation and PDF manipulation can be. Try it today!

< PREVIOUS
tailwind npm (How It Works For Developers)
NEXT >
Moment.js (How It Works For Developers)

Ready to get started? Version: 2024.9 just released

Free npm Install View Licenses >