date-fns NPM(開發者的使用方法)
在 React 應用中處理日期時,date-fns 是一個強大且輕量級的現代 JavaScript 日期工具程式庫,能輕鬆地操縱 JavaScript 日期。 date-fns 使用現有的本機日期資料型別,不會擴展核心物件以確保安全,也就是說,它會避免修改或新增功能到那些內建的日期資料型別,以防止潛在的錯誤或衝突。 在本文中,我們將探索如何將 date-fns 整合到您的 React 專案中並提供一些實用的範例。
為什麼選擇 date-fns?
date-fns 提供了幾個優勢:
- 模組化: 您可以只匯入需要的功能,以減少包的大小。
- 不可變: 使用純函式構建,因此這些函式不會改變原始的日期物件。
- 綜合: 提供廣泛的日期操作和格式化功能。
- 國際化: 支援多個語區。
快速入門
首先,通過 npm 安裝 date-fns 套件:
npm install date-fns
# or
yarn add date-fnsnpm install date-fns
# or
yarn add date-fns格式化日期
最常見的任務之一是使用 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;輸出

解析日期
您也可以從字串解析日期。 這是解析日期字串並以不同格式顯示的範例:
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;輸出

新增和減去日期
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;輸出

國際化
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;輸出

介紹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,使其適用於廣泛的開發環境。
簡單整合
using npm 套件輕鬆將 IronPDF 整合到您的 Node.js 應用中。 API 文件完善,便於在您的專案中加入 PDF 生成功能。
安裝
要安裝 IronPDF NPM 套件,請使用以下命令:
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64使用 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"接下來,導航至您的專案目錄:
cd date-pdfcd date-pdf安裝所需的套件:
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add date-fnsyarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add date-fns建立 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
}
}現在修改 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>
);
}輸出


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";結論
date-fns 是一個多功能且高效率的函式庫,提供強大但簡單且一致的工具集來在 React 應用中處理日期。 其模組化的方法允許您只包括所需的必要功能,保持包的大小小。 有了對日期操作和格式化的全面支援,date-fns 可以顯著提升您的 React 專案。
IronPDF for Node.js 是一個強健的庫,使開發者能夠無縫地生成、操作和程式化地處理 PDF 文件。 無論您需要將 HTML、URL 或其他格式轉換為 PDF,IronPDF 提供簡單的 API 來高效地完成這些任務。 它的功能範圍延伸包括處理 PDF 表單、應用安全措施、執行 OCR 等。








