NODE 說明 Moment.js(開發者的使用方法) Darrius Serrant 更新日期:7月 28, 2025 Download IronPDF npm 下載 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 在網頁開發的世界中,處理日期和時間格式是一個常見但棘手的任務。 幸運的是,有像 Moment.js 這樣的庫可以大大簡化這一過程。 在本文中,我們將深入探討 JavaScript 日期庫 Moment.js,探索其功能和優勢,以及如何在您的 JavaScript 和 Node.js 項目中有效運用它。 什麼是 Moment.js? Moment.js 是一款流行的 JavaScript 日期庫,旨在簡化顯示日期和時間的操作和格式化。 Moment.js 的核心是 moment 對象,它作為創建、解析和易於以人類可讀格式操作日期的基礎。 憑藉其強大的功能,開發人員可以在項目中無縫顯示人類可讀格式的日期,確保顯示日期表示和日期驗證的清晰性和一致性。 無論是在處理一個舊項目還是開展新的開發,Moment.js 始終是日期處理的首選,它使得開發人員能夠輕鬆進行日期查詢和範圍驗證,確保輸入數據的準確性,並按要求格式化日期。 Moment.js 的一個關鍵優點在於其能夠明確解析日期部分,使開發人員能夠精確地控制日期操作。 從提取日期範圍到查詢特定的日期組件,Moment.js 提供了解決不同日期相關任務所需的工具。 此外,Moment.js 不僅限於基本日期操作,還提供 Moment Timezone 插針以支持時區轉換。 儘管處於維護模式,但 Moment.js 仍然因其信賴性和處理日期和時間操作的多功能性被全球開發者依賴。 功能和優勢 簡單的 API:Moment.js 提供了一個直觀且易於使用的 API,隱藏了處理 JavaScript 中日期和時間的複雜性。 其語法簡潔且直觀,使得所有技能水平的開發者都可以輕鬆學習。 解析和格式化:使用 Moment.js,解析和格式化日期變得非常簡單。 無論您需要將日期字符串解析為 JavaScript 的 Date 對象,還是以特定方式格式化日期以便顯示,Moment.js 都提供了多種選擇以滿足您的需求。 操作:需要對日期添加或減去天、月或年嗎? Moment.js 使日期操作變得簡單,通過其 add 和 subtract 方法。 您還可以進行相對日期計算,例如確定兩個日期之間的差異並以不同單位(例如天、時、分)進行計算。 驗證:在許多應用中,驗證日期對於確保數據完整性至關重要。 Moment.js 提供了強大的驗證功能,使您可以檢查給定的日期字符串是否根據指定的格式有效。 時區支持:處理時區可能很具挑戰性,但 Moment.js 通過其內建的時區功能簡化了這個過程。 您可以輕鬆地在不同時區之間轉換日期或在特定時區顯示日期。 本地化:Moment.js 支持本地化,允許您根據用戶的地區,小顯示不同語言和格式的日期和時間。 插件生態系統:儘管 Moment.js 本身已提供豐富的功能,但它還擁有一個蓬勃發展的插件生態系統,可以進一步擴展其功能。 無論您是需要額外的格式選項、支持日曆,或與其他庫集成,都有可能找到合適的 Moment.js 插針來滿足您的需求。 開始使用 Moment.js 要在您的項目中使用 Moment.js,可以直接在 HTML 文件中通過 script 標籤包含。 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script> HTML 或者,您可以通過 npm 或 yarn 安裝 Moment.js 以用於 Node.js。 這將更新您的項目狀態,帶有創建和安裝的 moment。 npm install moment npm install moment SHELL 在項目中使用 Moment.js 一旦將 Moment.js 包含在你的項目中,您就可以開始使用其功能。 1. 解析日期字符串 const moment = require('moment'); // Parse a date string using Moment.js const date = moment("2024-05-25"); // Display the parsed date created explicitly console.log("Date created explicitly:", date); const moment = require('moment'); // Parse a date string using Moment.js const date = moment("2024-05-25"); // Display the parsed date created explicitly console.log("Date created explicitly:", date); JAVASCRIPT 說明 此代碼片段展示了如何通過解析日期字符串創建 moment 對象。 字符串 "2024-05-25" 表示 2024 年 5 月 25 日,Moment.js 自動將其轉換為 Date 對象,然後可以根據需要進行操作和格式化。 2. 格式化日期 const moment = require('moment'); // Parse a date string using moment object const date = moment("2024-05-25"); // Format and display the date console.log(date.format("MMMM Do YYYY, h:mm:ss a")); // May 25th 2024, 12:00:00 am const moment = require('moment'); // Parse a date string using moment object const date = moment("2024-05-25"); // Format and display the date console.log(date.format("MMMM Do YYYY, h:mm:ss a")); // May 25th 2024, 12:00:00 am JAVASCRIPT 說明 這裡使用 format() 方法根據指定的格式字符串格式化日期對象。 在本例中,"MMMM Do YYYY, h:mm:ss a" 格式化日期為 "May 25th 2024, 12:00:00 am"。 Moment.js 提供了多種格式選項,以根據您的需求自定義輸出。 3. 操作日期 const moment = require('moment'); // Parse a date string const date = moment("2024-05-25"); // Add 7 days to the date and format it console.log(date.add(7, 'days').format("YYYY-MM-DD")); // 2024-06-01 const moment = require('moment'); // Parse a date string const date = moment("2024-05-25"); // Add 7 days to the date and format it console.log(date.add(7, 'days').format("YYYY-MM-DD")); // 2024-06-01 JAVASCRIPT 說明 使用 add() 方法通過增加或減去指定的時間量來操作日期。在此範例中,日期增加了 7 天,結果為 2024 年 6 月 1 日。然後使用 "YYYY-MM-DD" 格式對日期進行格式化。 4. 驗證日期 const moment = require('moment'); // Validate a date string console.log(moment("2024-02-30", "YYYY-MM-DD").isValid()); // false const moment = require('moment'); // Validate a date string console.log(moment("2024-02-30", "YYYY-MM-DD").isValid()); // false JAVASCRIPT 說明 Moment.js 提供了 isValid() 方法來檢查日期的驗證。 它檢查給定的日期字符串是否根據指定的格式有效。 在此範例中,日期 "2024-02-30" 無效,因為 2 月不能出現 30 號,所以輸出為 false。 5. 時區轉換 const moment = require('moment-timezone'); // Parse a date string const date = moment("2024-05-25"); // Convert the date to a different timezone and format it console.log(date.tz('America/New_York').format("YYYY-MM-DD HH:mm:ss")); // 2024-05-24 20:00:00 const moment = require('moment-timezone'); // Parse a date string const date = moment("2024-05-25"); // Convert the date to a different timezone and format it console.log(date.tz('America/New_York').format("YYYY-MM-DD HH:mm:ss")); // 2024-05-24 20:00:00 JAVASCRIPT 說明 Moment.js 支持使用 tz() 方法進行時區轉換。 在本範例中,原始日期被轉換為 "America/New_York" 時區,結果為不同的輸出時間。然後使用 "YYYY-MM-DD HH:mm:ss" 格式對新日期進行格式化。 請注意,為了支持時區,我們使用了 moment-timezone 包來處理所有的地區設定。 使用 Moment.js 和 IronPDF 增強 PDF:動態添加日期 在現代網頁開發中,動態創建和操作 PDF 文檔是一項常見需求。 Node.js 的 IronPDF 庫提供強大的工具輕鬆生成和編輯 PDF。 結合 IronPDF 和 Moment.js,在處理日期和時間時,使得向 PDF 文檔添加動態的日期信息變得可能。 IronPDF 簡介 - Node.js PDF 库 IronPDF 為 Node.js 應用在無縫生成、編輯和操作 PDF 文檔方面提供了一個多功能且強大的解決方案。 這個強大的庫為開發者提供了一整套功能,包括可從 URL、HTML 內容或現有文檔輕鬆創建 PDF。 通過 IronPDF,容易的將文本、圖像或數字簽名添加到 PDF 等任務變得流暢,增強了生成文檔的功能和外觀。 此外,IronPDF 提供了高級功能的廣泛支持,如條形碼生成、加密和 PDF/A 合規性,確保兼容性和可靠性,適應不同的使用案例。 無論您在生成報告、發票還是交互式表單,IronPDF 提供了工具和靈活性來提升 Node.js 項目中的 PDF 生成工作流程。 要開始並獲取更多關於 IronPDF 功能的詳情,請訪問這個文檔頁面。 將 Moment.js 與 IronPDF 集成 下面是一個展示 Moment.js 和 IronPDF 如何輕鬆融合的示例,展示這種合作如何提高 PDF 創建中的動態日期處理。 將當前日期添加到 PDF 中 import { PdfDocument } from "@ironsoftware/ironpdf"; import moment from "moment"; (async () => { // Create a new PDF document const pdf = new PdfDocument(); // Generate current date using Moment.js const currentDate = moment().format("MMMM Do YYYY"); // Add the current date to the PDF pdf.append(`<p>Today's Date: ${currentDate}</p>`); // Save the PDF await pdf.saveAs("pdf_with_date.pdf"); })(); import { PdfDocument } from "@ironsoftware/ironpdf"; import moment from "moment"; (async () => { // Create a new PDF document const pdf = new PdfDocument(); // Generate current date using Moment.js const currentDate = moment().format("MMMM Do YYYY"); // Add the current date to the PDF pdf.append(`<p>Today's Date: ${currentDate}</p>`); // Save the PDF await pdf.saveAs("pdf_with_date.pdf"); })(); JAVASCRIPT 在此示例中,使用 Moment.js 生成指定格式 ("MMMM Do YYYY") 的當前日期,然後將其添加到用 IronPDF 創建的 PDF 文檔中。 將時間戳添加到 PDF 中 import { PdfDocument } from "@ironsoftware/ironpdf"; import moment from "moment"; (async () => { // Create a new PDF document const pdf = new PdfDocument(); // Generate current timestamp using Moment.js const timestamp = moment().format("MMMM Do YYYY, h:mm:ss a"); // Add the timestamp to the PDF pdf.append(`<p>Timestamp: ${timestamp}</p>`); // Save the PDF await pdf.saveAs("pdf_with_timestamp.pdf"); })(); import { PdfDocument } from "@ironsoftware/ironpdf"; import moment from "moment"; (async () => { // Create a new PDF document const pdf = new PdfDocument(); // Generate current timestamp using Moment.js const timestamp = moment().format("MMMM Do YYYY, h:mm:ss a"); // Add the timestamp to the PDF pdf.append(`<p>Timestamp: ${timestamp}</p>`); // Save the PDF await pdf.saveAs("pdf_with_timestamp.pdf"); })(); JAVASCRIPT 在此示例中,利用 Moment.js 生成包含日期和時間的時間戳,然後添加到 PDF 文檔中。 自定義日期格式 import { PdfDocument } from "@ironsoftware/ironpdf"; import moment from "moment"; (async () => { // Create a new PDF document const pdf = new PdfDocument(); // Generate a custom date format using Moment.js const customDate = moment().format("dddd, MMMM Do YYYY"); // Add the custom date format to the PDF pdf.append(`<p>Custom Date Format: ${customDate}</p>`); // Save the PDF await pdf.saveAs("pdf_with_custom_date.pdf"); })(); import { PdfDocument } from "@ironsoftware/ironpdf"; import moment from "moment"; (async () => { // Create a new PDF document const pdf = new PdfDocument(); // Generate a custom date format using Moment.js const customDate = moment().format("dddd, MMMM Do YYYY"); // Add the custom date format to the PDF pdf.append(`<p>Custom Date Format: ${customDate}</p>`); // Save the PDF await pdf.saveAs("pdf_with_custom_date.pdf"); })(); JAVASCRIPT 這裡,Moment.js 讓開發人員可以根據他們的要求定義自定義日期格式,從而提供靈活性來選擇日期在 PDF 文檔內的顯示方式。 您可以訪問這個即用的代碼範例頁面以獲得更高級使用 IronPDF 的範例。 查看更多詳細、結構化的API 參考以熟悉其框架。 結論 Moment.js 是處理 JavaScript 中日期和時間的強大工具。 其簡單性、靈活性和豐富的功能集合使其成為構建涉及日期和時間操作的網頁應用開發者的寶貴資產。 無論您在構建簡單的網站還是複雜的網頁應用,Moment.js 可以幫助簡化您的開發過程,確保在不同場景下準確處理日期和時間。 Moment.js 是 IronPDF 的一個寶貴伴侶,使開發者能夠輕鬆地將日期信息動態添加到 PDF 文檔中。 通過將 Moment.js 與 IronPDF 集成,開發者可以增強其 PDF 的功能和視覺吸引力,無論是添加當前日期、時間戳還是自定義日期格式。 這一強大的組合賦予開發者創建符合他們具體需求的動態和信息豐富的 PDF 文檔的能力。 無論您是在生成報告、發票還是任何其他類型的文檔中,Moment.js 和 IronPDF 提供了一個無縫解決方案,以在您的 PDF 中集成日期信息。 IronPDF 提供了免費試用的 $799 價格,投資 IronPDF 將解鎖一個關於 PDF 生成需求的新世界。 立即體驗IronPDF的便捷、強大和高效,提升您的文檔工作流程到新的高度。 Darrius Serrant 立即與工程團隊聊天 全棧軟件工程師 (WebOps) Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。 相關文章 更新日期 7月 28, 2025 linkify-react(使用方法:開發者指南) Linkify React 是一個輕量和容易使用的 npm 套件,能自動將含有 URLs 的純文本轉換 閱讀更多 更新日期 6月 22, 2025 next-auth NPM(開發者的使用方法) NextAuth.js 是開放源代碼驗證庫為 Next.js 應用程式專門提供實現身份驗證的一種靈活且安全的方法。 閱讀更多 更新日期 6月 22, 2025 Koa node js(開發者的使用方法) Koa.js 是一個為 Node.js 的生成 Web 框架,擅長支持异步功能,讓開發人員可以輕松編寫非同步中間件。 閱讀更多 Day.js npm(開發者的使用方法)BPMN JS npm(開發者的使用方...
更新日期 6月 22, 2025 next-auth NPM(開發者的使用方法) NextAuth.js 是開放源代碼驗證庫為 Next.js 應用程式專門提供實現身份驗證的一種靈活且安全的方法。 閱讀更多
更新日期 6月 22, 2025 Koa node js(開發者的使用方法) Koa.js 是一個為 Node.js 的生成 Web 框架,擅長支持异步功能,讓開發人員可以輕松編寫非同步中間件。 閱讀更多