NODE 說明 date-fns NPM(開發者的使用方法) Darrius Serrant 更新日期:6月 22, 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 在 React 應用程式中處理日期時,date-fns 是一個強大且輕量級的現代 JavaScript 日期工具庫,可以輕鬆操作 JavaScript 日期。 date-fns 使用現有的本地日期數據類型,並且為了安全起見不會擴展核心對象,這意味著它將避免修改或增加內建日期數據類型的功能,這可能會導致潛在的錯誤或衝突。 在本文中,我們將探討如何將 date-fns 整合到您的 React 項目中,並提供一些實用的示例。 為什麼選擇 date-fns? date-fns 提供了多項優勢: 模組化:您可以僅導入所需的函數,以減少包的大小。 不可變:它是基於純函數構建的,因此這些函數不會更改原始日期對象。 全面性:提供廣泛的日期操作和格式化函數。 國際化:支持多種語言環境。 開始使用 首先,通過 npm 安裝 date-fns npm 包: npm install date-fns # or yarn add date-fns npm install date-fns # or yarn add date-fns SHELL 格式化日期 格式化日期是最常見的任務之一,使用 date-fns。 我們來創建一個簡單的組件,以可讀格式顯示您所在時區的當前日期。 import React from 'react'; import { format } from 'date-fns'; // A functional component to format the current date using date-fns const FormattedDate = () => { const currentDate = new Date(); // Get current date const formattedDate = format(currentDate, 'MMMM do, yyyy'); // Format date as "Month day, year" return <p>{formattedDate}</p>; // Render formatted date in a paragraph }; export default FormattedDate; import React from 'react'; import { format } from 'date-fns'; // A functional component to format the current date using date-fns const FormattedDate = () => { const currentDate = new Date(); // Get current date const formattedDate = format(currentDate, 'MMMM do, yyyy'); // Format date as "Month day, year" return <p>{formattedDate}</p>; // Render formatted date in a paragraph }; export default FormattedDate; JAVASCRIPT 輸出 解析日期 您還可以從字串解析日期。 這裡是一個解析日期字串並以不同格式顯示的示例: import React from 'react'; import { parse, format } from 'date-fns'; // A functional component to parse and format a date string const ParsedDate = () => { const dateString = '2024-06-23'; // Define a date string const parsedDate = parse(dateString, 'yyyy-MM-dd', new Date()); // Parse date string into a JavaScript Date object const formattedDate = format(parsedDate, 'MMMM do, yyyy'); // Format parsed date return <p>{formattedDate}</p>; // Render formatted date }; export default ParsedDate; import React from 'react'; import { parse, format } from 'date-fns'; // A functional component to parse and format a date string const ParsedDate = () => { const dateString = '2024-06-23'; // Define a date string const parsedDate = parse(dateString, 'yyyy-MM-dd', new Date()); // Parse date string into a JavaScript Date object const formattedDate = format(parsedDate, 'MMMM do, yyyy'); // Format parsed date return <p>{formattedDate}</p>; // Render formatted date }; export default ParsedDate; JAVASCRIPT 輸出 添加和減去日期 date-fns 使得從日期中添加或減去時間變得簡單容易。 這是一個將當前日期加上7天的示例: import React from 'react'; import { addDays, format } from 'date-fns'; // A functional component to add days to the current date and format it const AddDaysExample = () => { const currentDate = new Date(); // Current date const futureDate = addDays(currentDate, 7); // Add 7 days to the current date const formattedDate = format(futureDate, 'MMMM do, yyyy'); // Format the new date return <p>{formattedDate}</p>; // Render formatted date }; export default AddDaysExample; import React from 'react'; import { addDays, format } from 'date-fns'; // A functional component to add days to the current date and format it const AddDaysExample = () => { const currentDate = new Date(); // Current date const futureDate = addDays(currentDate, 7); // Add 7 days to the current date const formattedDate = format(futureDate, 'MMMM do, yyyy'); // Format the new date return <p>{formattedDate}</p>; // Render formatted date }; export default AddDaysExample; JAVASCRIPT 輸出 國際化 date-fns 支持多種語言環境。 要使用特定語言環境,您需要將其導入並傳遞給格式化函數: import React from 'react'; import { format } from 'date-fns'; import { fr } from 'date-fns/locale'; // A functional component to format the current date using a specific locale const FrenchDate = () => { const currentDate = new Date(); // Current date const formattedDate = format(currentDate, 'MMMM do, yyyy', { locale: fr }); // Format date in French locale return <p>{formattedDate}</p>; // Render formatted date }; export default FrenchDate; import React from 'react'; import { format } from 'date-fns'; import { fr } from 'date-fns/locale'; // A functional component to format the current date using a specific locale const FrenchDate = () => { const currentDate = new Date(); // Current date const formattedDate = format(currentDate, 'MMMM do, yyyy', { locale: fr }); // Format date in French locale return <p>{formattedDate}</p>; // Render formatted date }; export default FrenchDate; JAVASCRIPT 輸出 介紹IronPDF IronPDF for Node.js 是一個強大的 Node.js PDF 庫,允許開發者在他們的 Node.js 項目中生成和編輯 PDFs。 無論您需要從 HTML 創建 PDF、操作現有的 PDF 還是將網頁轉換為 PDF 格式,IronPDF 都能滿足您的需求。 關鍵特性 HTML 到 PDF 轉換 輕鬆將 HTML 內容轉換為 PDF 文檔。 此功能特別適合從網頁內容生成動態 PDF。 URL 到 PDF 轉換 直接從 URL 生成 PDF,允許您捕獲網頁的內容並以程式方式將其保存為 PDF 文件。 PDF 操作 輕鬆合併、拆分和操作現有的 PDF 文檔。 IronPDF 提供了附加頁面、拆分文檔等功能。 PDF 安全性 通過設置密碼或應用數字簽名來保護您的 PDF 文件。 IronPDF 提供選項以保護您的機密文件免遭未授權訪問。 高品質輸出 生成的 PDF 文檔具有精確的文字、圖片和格式渲染,具有高品質。 IronPDF 確保您生成的 PDF 保持對原始內容的保真度。 跨平台相容性 IronPDF 與包括 Windows、Linux 和 macOS 在內的多個平台相容,使其適合於多種開發環境。 簡單的整合 輕鬆將 IronPDF 整合到您的 Node.js 應用中,使用其 npm 包。 API 文檔完善,使其易於將 PDF 生成功能納入您的項目。 安裝 要安裝 IronPDF NPM 包,請使用以下命令: yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64 yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64 SHELL 使用 IronPDF 和 date-fns 生成 PDF 文檔 安裝依賴:首先,使用以下命令創建一個新的 Next.js 項目(如果尚未創建),參見這裡 npx create-next-app@latest date-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter" npx create-next-app@latest date-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter" SHELL 接下來,導航至您的項目目錄: cd date-pdf cd date-pdf SHELL 安裝所需的包: yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64 yarn add date-fns yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64 yarn add date-fns SHELL 創建 PDF 現在,我們來創建一個使用 IronPDF 生成 PDF 的簡單示例。 在您的 Next.js 組件中(例如 pages/index.tsx),添加以下代碼: PDF 生成 API:第一步是創建一個後端 API 來生成 PDF 文檔。 由於 IronPDF 只能在服務器端運行,我們需要創建一個用戶想要生成 PDF 時可以調用的 API。 在路徑 pages/api/pdf.js 中創建一個文件並添加如下內容。 IronPDF 需要授權密鑰,您可以從許可頁面獲得,並將其放在下面的代碼中。 // pages/api/pdf.js import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf"; import { format } from 'date-fns'; // Apply your IronPDF license key IronPdfGlobalConfig.getConfig().licenseKey = "Your license key"; export default async function handler(req, res) { try { const currentDate = new Date(); // Get the current date const formattedDate = format(currentDate, 'MMMM do, yyyy'); // Format the date let content = "<h1>Demo React Hook Form and Generate PDF Using IronPDF</h1>"; content += "<p>Date:" + currentDate + "</p>"; content += "<p>Formatted Date:" + formattedDate + "</p>"; const pdf = await PdfDocument.fromHtml(content); // Generate PDF from HTML content const data = await pdf.saveAsBuffer(); // Save as buffer console.error("data PDF:", data); // Log the PDF data res.setHeader("Content-Type", "application/pdf"); // Set response headers res.setHeader( "Content-Disposition", "attachment; filename=awesomeIron.pdf", ); res.send(data); // Send PDF data as response } catch (error) { console.error("Error generating PDF:", error); // Log errors res.status(500).end(); // End response on error } } // pages/api/pdf.js import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf"; import { format } from 'date-fns'; // Apply your IronPDF license key IronPdfGlobalConfig.getConfig().licenseKey = "Your license key"; export default async function handler(req, res) { try { const currentDate = new Date(); // Get the current date const formattedDate = format(currentDate, 'MMMM do, yyyy'); // Format the date let content = "<h1>Demo React Hook Form and Generate PDF Using IronPDF</h1>"; content += "<p>Date:" + currentDate + "</p>"; content += "<p>Formatted Date:" + formattedDate + "</p>"; const pdf = await PdfDocument.fromHtml(content); // Generate PDF from HTML content const data = await pdf.saveAsBuffer(); // Save as buffer console.error("data PDF:", data); // Log the PDF data res.setHeader("Content-Type", "application/pdf"); // Set response headers res.setHeader( "Content-Disposition", "attachment; filename=awesomeIron.pdf", ); res.send(data); // Send PDF data as response } catch (error) { console.error("Error generating PDF:", error); // Log errors res.status(500).end(); // End response on error } } JAVASCRIPT 現在修改index.js並添加如下代碼: import Head from "next/head"; import styles from "../styles/Home.module.css"; import React, { useState, useEffect } from "react"; import { format } from 'date-fns'; // React component for the home page export default function Home() { const [text, setText] = useState(""); useEffect(() => { const currentDate = new Date(); // Get a new date instance const formattedDate = format(currentDate, 'MMMM do, yyyy'); // Format the date setText(formattedDate); // Set formatted date to state }, []); const generatePdf = async () => { try { const response = await fetch("/api/pdf-datefns?f=" + text); // Fetch the PDF from API const blob = await response.blob(); // Convert to blob const url = window.URL.createObjectURL(new Blob([blob])); // Create URL for download const link = document.createElement("a"); link.href = url; link.setAttribute("download", "awesomeIron.pdf"); // Set download attribute document.body.appendChild(link); link.click(); // Simulate click to download link.parentNode.removeChild(link); } catch (error) { console.error("Error generating PDF:", error); // Log errors } }; return ( <div className={styles.container}> <Head> <title>Generate PDF Using IronPDF</title> <link rel="icon" href="/favicon.ico" /> </Head> <main> <h1>Demo Date-fns and Generate PDF Using IronPDF</h1> <p> Formatted Data: {text} </p> <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}> Generate PDF </button> </main> <style jsx>{` main { padding: 5rem 0; flex: 1; display: flex; flex-direction: column; justify-content: center; align-items: center; } footer { width: 100%; height: 100px; border-top: 1px solid #eaeaea; display: flex; justify-content: center; align-items: center; } footer img { margin-left: 0.5rem; } footer a { display: flex; justify-content: center; align-items: center; text-decoration: none; color: inherit; } code { background: #fafafa; border-radius: 5px; padding: 0.75rem; font-size: 1.1rem; font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace; } `}</style> <style jsx global>{` html, body { padding: 0; margin: 0; font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; } * { box-sizing: border-box; } `}</style> </div> ); } import Head from "next/head"; import styles from "../styles/Home.module.css"; import React, { useState, useEffect } from "react"; import { format } from 'date-fns'; // React component for the home page export default function Home() { const [text, setText] = useState(""); useEffect(() => { const currentDate = new Date(); // Get a new date instance const formattedDate = format(currentDate, 'MMMM do, yyyy'); // Format the date setText(formattedDate); // Set formatted date to state }, []); const generatePdf = async () => { try { const response = await fetch("/api/pdf-datefns?f=" + text); // Fetch the PDF from API const blob = await response.blob(); // Convert to blob const url = window.URL.createObjectURL(new Blob([blob])); // Create URL for download const link = document.createElement("a"); link.href = url; link.setAttribute("download", "awesomeIron.pdf"); // Set download attribute document.body.appendChild(link); link.click(); // Simulate click to download link.parentNode.removeChild(link); } catch (error) { console.error("Error generating PDF:", error); // Log errors } }; return ( <div className={styles.container}> <Head> <title>Generate PDF Using IronPDF</title> <link rel="icon" href="/favicon.ico" /> </Head> <main> <h1>Demo Date-fns and Generate PDF Using IronPDF</h1> <p> Formatted Data: {text} </p> <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}> Generate PDF </button> </main> <style jsx>{` main { padding: 5rem 0; flex: 1; display: flex; flex-direction: column; justify-content: center; align-items: center; } footer { width: 100%; height: 100px; border-top: 1px solid #eaeaea; display: flex; justify-content: center; align-items: center; } footer img { margin-left: 0.5rem; } footer a { display: flex; justify-content: center; align-items: center; text-decoration: none; color: inherit; } code { background: #fafafa; border-radius: 5px; padding: 0.75rem; font-size: 1.1rem; font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace; } `}</style> <style jsx global>{` html, body { padding: 0; margin: 0; font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; } * { box-sizing: border-box; } `}</style> </div> ); } JAVASCRIPT 輸出 PDF IronPDF 授權 IronPDF。 在此處放置許可證密鑰: import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf"; // Apply your IronPDF license key IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here"; import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf"; // Apply your IronPDF license key IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here"; JAVASCRIPT 結論 date-fns 是一個多功能且高效的庫,為在 React 應用中處理日期提供了強大而簡單一致的工具集。 其模組化方法可讓您只加入所需的必要函數,保持包的大小較小。 具有全面的日期操作和格式化支持,date-fns 可以顯著增強您的 React 項目。 IronPDF for Node.js 是一個強大的庫,能夠讓開發者以程式方式無縫生成、操作和使用 PDF 文檔。 無論您需要將 HTML、URL 或其他格式轉換為 PDF,IronPDF 都提供簡單的 API 以高效地完成這些任務。 其功能還擴展到處理 PDF 表單、應用安全措施、執行 OCR 等。 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 框架,擅長支持异步功能,讓開發人員可以輕松編寫非同步中間件。 閱讀更多 memcached npm(開發者的使用方法)express validator npm(開發者...
更新日期 6月 22, 2025 next-auth NPM(開發者的使用方法) NextAuth.js 是開放源代碼驗證庫為 Next.js 應用程式專門提供實現身份驗證的一種靈活且安全的方法。 閱讀更多
更新日期 6月 22, 2025 Koa node js(開發者的使用方法) Koa.js 是一個為 Node.js 的生成 Web 框架,擅長支持异步功能,讓開發人員可以輕松編寫非同步中間件。 閱讀更多