Day.js npm (How It Works For Developers)
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 similarly 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.
Key Features
Here are some key features of the Day.js library:
- Lightweight: With its tiny size and advanced formatting options, Day.js ensures that your application remains fast and efficient.
- Immutable: Day.js objects are immutable, meaning that methods do not mutate the original object, but instead return new instances.
- Chainable API: Methods in Day.js can be chained together, making code more readable and concise.
- Internationalization: Day.js supports multiple locales, allowing for easy localization of dates and times.
- Plugin System: A modular plugin system allows you to extend Day.js functionality without bloating the core library.
- 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
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');
2. Formatting Dates
Day.js provides a flexible and powerful way to format dates:
const date = dayjs('2023-05-25');
// Format date as "YYYY-MM-DD"
console.log(date.format('YYYY-MM-DD')); // 2023-05-25
// Format date as "dddd, MMMM D, YYYY"
console.log(date.format('dddd, MMMM D, YYYY')); // Thursday, May 25, 2023
const date = dayjs('2023-05-25');
// Format date as "YYYY-MM-DD"
console.log(date.format('YYYY-MM-DD')); // 2023-05-25
// Format date as "dddd, MMMM D, YYYY"
console.log(date.format('dddd, MMMM D, YYYY')); // Thursday, May 25, 2023
3. Parsing Dates
Day.js can parse date objects from strings and display dates in various formats:
const date1 = dayjs('2023-05-25');
const date2 = dayjs('05/25/2023', 'MM/DD/YYYY');
// Check if the dates are the same
console.log(date1.isSame(date2)); // true
const date1 = dayjs('2023-05-25');
const date2 = dayjs('05/25/2023', 'MM/DD/YYYY');
// Check if the dates are the same
console.log(date1.isSame(date2)); // true
4. Manipulating Dates
Day.js allows for easy manipulation of dates with its chainable API:
const date = dayjs('2023-05-25');
// Add one week to the date
const nextWeek = date.add(1, 'week');
// Subtract one month from the date
const lastMonth = date.subtract(1, 'month');
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');
// Add one week to the date
const nextWeek = date.add(1, 'week');
// Subtract one month from the date
const lastMonth = date.subtract(1, 'month');
console.log(nextWeek.format('YYYY-MM-DD')); // 2023-06-01
console.log(lastMonth.format('YYYY-MM-DD')); // 2023-04-25
5. Comparing Dates
Comparing dates in Day.js is simple and intuitive:
const date1 = dayjs('2023-05-25');
const date2 = dayjs('2023-06-01');
// Check if date1 is before date2
console.log(date1.isBefore(date2)); // true
// Check if date1 is after date2
console.log(date1.isAfter(date2)); // false
// Check if date1 is the same as date2
console.log(date1.isSame(date2)); // false
const date1 = dayjs('2023-05-25');
const date2 = dayjs('2023-06-01');
// Check if date1 is before date2
console.log(date1.isBefore(date2)); // true
// Check if date1 is after date2
console.log(date1.isAfter(date2)); // false
// Check if date1 is the same as date2
console.log(date1.isSame(date2)); // false
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');
// Extend Day.js with plugins
dayjs.extend(localizedFormat);
dayjs.extend(localeData);
dayjs.extend(updateLocale);
// Set locale to French
dayjs.locale('fr');
// Display date in localized format
console.log(dayjs().format('dddd, MMMM D, YYYY')); // jeudi, mai 25, 2023
// Customize locale
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']
});
// Display date in customized localized format
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');
// Extend Day.js with plugins
dayjs.extend(localizedFormat);
dayjs.extend(localeData);
dayjs.extend(updateLocale);
// Set locale to French
dayjs.locale('fr');
// Display date in localized format
console.log(dayjs().format('dddd, MMMM D, YYYY')); // jeudi, mai 25, 2023
// Customize locale
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']
});
// Display date in customized localized format
console.log(dayjs().format('dddd, MMMM D, YYYY')); // jeudi, mai 25, 2023
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.
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
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");
})();
Here is the output:
You can also use ready-to-use code examples to immediately get started with the library in your Node.js application. For further exploration, 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!