節點幫助

Day.js npm (其對開發者的作用)

發佈 2024年9月29日
分享:

由於內建 Date 對象的限制和特性,在 JavaScript 中處理日期和時間一直是一項具有挑戰性的任務。 儘管原生的 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
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install dayjs
VB   C#

基本用法

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');
const dayjs = require( 'dayjs');
' Current date and time
const now = dayjs()
' Specific date and time
const specificDate = dayjs( '2023-05-25');
VB   C#

2. 格式化日期

Day.js 提供了一種靈活且強大的新實例方法來格式化日期:

const date = dayjs('2023-05-25');
console.log(date.format('YYYY-MM-DD')); // 2023-05-25
console.log(date.format('dddd, MMMM D, YYYY')); // Thursday, May 25, 2023
const date = dayjs('2023-05-25');
console.log(date.format('YYYY-MM-DD')); // 2023-05-25
console.log(date.format('dddd, MMMM D, YYYY')); // Thursday, May 25, 2023
const [date] = dayjs( '2023-05-25');
console.log([date].format( 'YYYY-MM-DD')); ' 2023-05-25
console.log([date].format( 'dddd, MMMM D, YYYY')); ' Thursday, May 25, 2023
VB   C#

3. 解析日期

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

const date1 = dayjs('2023-05-25');
const date2 = dayjs('05/25/2023', 'MM/DD/YYYY');
console.log(date1.isSame(date2)); // true
const date1 = dayjs('2023-05-25');
const date2 = dayjs('05/25/2023', 'MM/DD/YYYY');
console.log(date1.isSame(date2)); // true
const date1 = dayjs( '2023-05-25');
const date2 = dayjs( '05/25/2023', 'MM/DD/YYYY');
console.log(date1.isSame(date2)) ' true
VB   C#

4. 操作日期

Day.js 透過其可鏈式操作的 API,允許輕鬆處理日期:

const date = dayjs('2023-05-25');
const nextWeek = date.add(1, 'week'); // Updated Value
const lastMonth = date.subtract(1, 'month'); // Updated Value
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');
const nextWeek = date.add(1, 'week'); // Updated Value
const lastMonth = date.subtract(1, 'month'); // Updated Value
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');
const nextWeek = [date].add(1, 'week'); ' Updated Value
const lastMonth = [date].subtract(1, 'month'); ' Updated Value
console.log(nextWeek.format( 'YYYY-MM-DD')); ' 2023-06-01
console.log(lastMonth.format( 'YYYY-MM-DD')); ' 2023-04-25
VB   C#

5. 比較日期

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

const date1 = dayjs('2023-05-25');
const date2 = dayjs('2023-06-01');
console.log(date1.isBefore(date2)); // true
console.log(date1.isAfter(date2)); // false
console.log(date1.isSame(date2)); // false
const date1 = dayjs('2023-05-25');
const date2 = dayjs('2023-06-01');
console.log(date1.isBefore(date2)); // true
console.log(date1.isAfter(date2)); // false
console.log(date1.isSame(date2)); // false
const date1 = dayjs( '2023-05-25');
const date2 = dayjs( '2023-06-01');
console.log(date1.isBefore(date2)) ' true
console.log(date1.isAfter(date2)) ' false
console.log(date1.isSame(date2)) ' false
VB   C#

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');
dayjs.extend(localizedFormat);
dayjs.extend(localeData);
dayjs.extend(updateLocale);
dayjs.locale('fr');
console.log(dayjs().format('dddd, MMMM D, YYYY')); // jeudi, mai 25, 2023
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']
});
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');
dayjs.extend(localizedFormat);
dayjs.extend(localeData);
dayjs.extend(updateLocale);
dayjs.locale('fr');
console.log(dayjs().format('dddd, MMMM D, YYYY')); // jeudi, mai 25, 2023
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']
});
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');
dayjs.extend(localizedFormat)
dayjs.extend(localeData)
dayjs.extend(updateLocale)
dayjs.locale( 'fr');
console.log(dayjs().format( 'dddd, MMMM D, YYYY')); ' jeudi, mai 25, 2023
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'] });
console.log(dayjs().format( 'dddd, MMMM D, YYYY')); ' jeudi, mai 25, 2023
VB   C#

在 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
npm i @ironsoftware/ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm i @ironsoftware/ironpdf
VB   C#

添加帶日期的數位簽章

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");
})();
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import dayjs from 'dayjs'; import { PdfDocument } from "@ironsoftware/ironpdf"; (async() => { const pdf = await PdfDocument.open("sample.pdf"); const signatureDate = dayjs().toDate(); 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" } }); await pdf.saveAs("signed_with_date.pdf"); })();
VB   C#

這是輸出:

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 的 起價 $749。 親自體驗強大的 PDF 生成和 PDF 操作功能。 立即試用!

< 上一頁
tailwind npm(它對開發人員的運作方式)
下一個 >
Moment.js(開發者如何使用)

準備開始了嗎? 版本: 2024.9 剛剛發布

免費 npm 安裝 查看許可證 >