跳過到頁腳內容
NODE 說明

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

由於內建Date對象的局限性和特性,在JavaScript中處理日期和時間歷來是一項具有挑戰性的任務。 雖然原生的Date對象提供了基本功能,但在可用性方面往往遜色,促使開發者尋求更強大的解決方案。 其中一個解決方案是Day.js,這是一個用於解析、驗證、操作和顯示日期和時間的極簡JavaScript程式庫。

本文探討了Day.js的功能、優點和用法,說明為何它成為開發者中的熱門選擇。

什麼是Day.js?

Day.js是一個輕量級的JavaScript程式庫,提供了一個簡單的API,用於在現代瀏覽器中正確顯示日期和時間。 它被設計為類似現代API Moment.js的替代品,一個廣泛使用但體積更大的程式庫。 Day.js的大小僅為2kB(gzip後),是對性能有關注的應用程式的一個極好選擇。 儘管體積小,Day.js程式庫是Moment.js的一個替代品,並提供覆蓋最常見用例的強大功能。

Day.js npm(對開發者的運作方式):圖1 - Day.js

主要功能

以下是Day.js程式庫的一些關鍵功能:

  1. 輕量級:其微小的體積和先進的格式選項確保您的應用程式保持快速和高效。
  2. 不可變: Day.js對象是不可變的,這意味著方法不會改變原始對象,而是返回新的實例。
  3. 可鏈式API: Day.js中的方法可以串聯在一起,使程式代碼更具可讀性且更簡潔。
  4. 國際化: Day.js支持多種地區,允許日期和時間的輕鬆本地化。
  5. 插件系統: 模塊化的插件系統允許您擴展Day.js的功能而不會擴充核心程式庫。
  6. 兼容性: Day.js被設計為與Moment.js API兼容,使得現有代碼庫易於遷移。

安裝

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

使用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這個多功能PDF生成和操作程式庫,可以讓開發者高效地處理PDF文件中的日期。

IronPDF - Node.js的PDF程式庫

IronPDF for Node.js是一個綜合性的程式庫,賦予開發者在Node.js應用程式中無縫創建、操作和互動PDF文件的能力。 IronPDF提供豐富的功能集,簡化了生成PDF文件的任務,如從HTML、網站URL或現有文檔生成PDF,添加文本、圖像和互動元素,並精確地將HTML轉換為PDF。

Day.js npm(對開發者的運作方式):圖2 - IronPDF

關於Node.js的IronPDF的更多詳細信息,請訪問此文檔頁面。

開始使用

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

 npm i @ironsoftware/ironpdf

向PDF中添加帶日期的數位簽名

IronPDF也支持向PDF添加數位簽名。 以下是如何使用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");
})();
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 來說,工作令人滿意因為它被重視且有實際影響。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me