跳過到頁腳內容
NODE 說明

Day.js npm(開發者的使用方法)

在JavaScript中處理日期和時間一直以來都是一項具有挑戰性的任務,這是由於內建Date物件的限制和怪癖所致。 雖然原生的Date物件提供基本的功能,但在可用性方面往往不足,這使得開發者尋求更強大的解決方案。 其中一種解決方案是Day.js,這是一個極簡的JavaScript庫,用於解析、驗證、操作和顯示日期和時間。

本文探討了Day.js的特性、優勢和使用方法,展示了為何它成為開發者中的受歡迎選擇。

什麼是Day.js?

Day.js是一個輕量級的JavaScript庫,提供一個簡單的API,用於正確地在現代瀏覽器中處理和顯示日期和時間。 它被設計為與同樣現代的API Moment.js的替代方案,後者是一個廣泛使用但更為沉重的庫。 Day.js的大小僅有2kB(壓縮),使其成為對性能敏感的應用程序的絕佳選擇。 儘管Day.js的體積小,但作為Moment.js的替代方案,它提供了強大的功能,涵蓋最常見的使用案例。

Day.js npm(如何對開發者起作用):圖1 - Day.js

關鍵特性

以下是Day.js庫的一些主要特點:

  1. 輕量化:Day.js以其微小的大小和高級格式化選項確保您的應用程序保持快速高效。
  2. 不可變:Day.js物件是不可變的,這意味著方法不會改變原始物件,而是返回新的實例。
  3. 鏈式API:Day.js中的方法可以鏈接在一起,使代碼更易讀和簡潔。
  4. 國際化:Day.js支持多語言環境,允許輕鬆地進行日期和時間的本地化。
  5. 插件系統:一個模塊化的插件系統允許您在不膨脹核心庫的情況下擴展Day.js的功能。
  6. 兼容性:Day.js被設計為與Moment.js API兼容,便於現有代碼庫的遷移。

安裝

Day.js可以通過npm或yarn輕鬆安裝。 它也可以通過CDN直接包含在您的HTML文件中。

使用npm

npm install dayjs
npm install dayjs
SHELL

基本用法

Day.js對時區的廣泛支持使開發人員能夠輕鬆管理本地時間並精確地進行時間操作任務。 借助其嚴格的解析功能,Day.js確保了日期和時間值的準確解釋,實現了可靠和一致的結果。 無論是減去時間還是更新值,Day.js都使處理日期和時間變得簡單,並提供創建新實例等附加功能以提高靈活性。

讓我們來看看一些使用Day.js的例子。

1. 創建日期

在Day.js中創建新的日期實例非常簡單。 以下範例展示了它:

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');
JAVASCRIPT

2. 日期格式化

Day.js提供了一種靈活又強大的方式來格式化日期:

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
JAVASCRIPT

3. 解析日期

Day.js可以從字符串解析日期物件,並以多種格式顯示日期:

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
JAVASCRIPT

4. 操作日期

Day.js允許通過其鏈式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
JAVASCRIPT

5. 比較日期

在Day.js中比較日期既簡單又直觀:

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
JAVASCRIPT

6. 本地化

Day.js支持國際化(i18n)以處理不同地區語言環境:

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
JAVASCRIPT

在Node.js中使用Day.js與IronPDF將日期添加到PDF中

結合Day.js這個輕量級JavaScript日期庫和IronPDF這個用於Node.js的多功能PDF生成和操作庫的強大功能,開發人員可以高效地處理PDF文件中的日期。

IronPDF - Node.js PDF庫

IronPDF對於Node.js來說是一個全面的庫,能夠讓開發者在他們的Node.js應用程序中無縫地創建、操作和交互PDF文件。 提供一整套豐富的功能,IronPDF簡化了從HTML、網站URL或現有文件生成PDF、添加文字、圖像和交互元素以及精確地將HTML轉換為PDF等任務。

Day.js npm(如何對開發者起作用):圖2 - IronPDF

有關IronPDF for Node.js的詳細信息,請訪問此文件頁面。

開始使用

首先,確保您已安裝必要的包。 您可以通過npm安裝Day.js和IronPDF:

 npm i @ironsoftware/ironpdf

添加帶有日期的數位簽名

IronPDF還支持在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");
})();
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");
})();
JAVASCRIPT

輸出如下:

Day.js npm(如何對開發者起作用):圖3 - PDF輸出

您還可以使用現成的代碼範例立即開始在您的Node.js應用程序中使用這個庫。 要進一步探索,您也可以訪問此API參考頁面。

結論

Day.js是一個強大且高效的JavaScript日期和時間管理庫。 它的輕量級特性、不變數據結構的支持和對Moment.js的兼容性,使其成為尋求處理日期和時間操作而不增加應用程序顯著負擔的開發人員的有吸引力的選擇。

通過將Day.js與IronPDF整合,開發人員可以輕鬆地在他們的PDF文件中處理日期。 無論是從URL或HTML字符串生成PDF,還是添加帶有時間戳的數位簽名,Day.js都提供了一種處理日期的簡單且強大的方式。 這種結合增強了您的Node.js應用程序的功能,允許進行強大且動態的PDF文件管理。

體驗IronPDF,起步價為$799。 親自看看PDF生成和PDF操作的強大功能。 今天就試試吧!

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。