NODE 帮助 date-fns NPM(开发者如何使用) Darrius Serrant 已更新:六月 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 项目中生成和编辑 PDF。 无论您是需要从 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,使其适合广泛的开发环境。 简单集成 轻松通过 npm 包将 IronPDF 集成到您的 Node.js 应用程序中。 API 有详细文档,使在您的项目中集成 PDF 生成功能变得简单直接。 安装 要安装 IronPDF NPM 包,使用以下命令: yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64 yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64 SHELL 使用 IronPDF 生成 PDF 文档并使用 date-fns 安装依赖项:首先,使用以下命令创建一个新的 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 仅在服务器端运行,因此需要创建一个 API 以在用户希望生成 PDF 时调用。 在路径 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 来说,他的工作令人满意,因为它被重视并产生真正的影响。 相关文章 已更新七月 28, 2025 linkify-react(它是如何工作的:开发者指南) Linkify React 是一个轻量且易于使用的 npm 包,可自动将包含 URL 的纯文本转换。 阅读更多 已更新六月 22, 2025 next-auth NPM(开发者如何使用) NextAuth.js 是一个针对 Next.js 应用程序的开源身份验证库,提供了一种灵活且安全的方式在 Web 应用中实现身份验证 阅读更多 已更新六月 22, 2025 Koa node js(开发者如何使用) Koa.js,一个为 Node.js 设计的新一代 Web 框架,以其异步函数支持著称,使开发者可以轻松编写异步中间件 阅读更多 memcached npm(开发者如何使用)express validator npm(开发者...
已更新六月 22, 2025 next-auth NPM(开发者如何使用) NextAuth.js 是一个针对 Next.js 应用程序的开源身份验证库,提供了一种灵活且安全的方式在 Web 应用中实现身份验证 阅读更多