跳過到頁腳內容
NODE 說明

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 i @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,從 $999 開始。 親眼見證PDF生成和PDF操作的強大功能。 今天就來試試吧!

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

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

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

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

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我