跳至頁尾內容
節點幫助

Day.js npm(開發者使用指南)

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

本文探討了 Day.js 的特性、優勢和用法,並闡述了它為何成為開發者的熱門選擇。

Day.js是什麼?

Day.js是一個輕量級的 JavaScript 函式庫,它提供了一個簡單的 API 來處理日期和時間,以便在現代瀏覽器中正確顯示日期和時間。 它的設計初衷是作為類似現代 API Moment.js 的替代方案,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 for 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 和 @ironsoftware/ironpdf

添加帶有日期的數位簽名

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文件管理。

體驗IronPDFs,起價只需$799 。 親眼見證PDF生成和PDF操作的強大功能。 今天就來試試吧!

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。