date-fns NPM(開發者的使用方法)
在 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-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 適用於 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 在內的各種平台相容,使其適用於各種開發環境。
簡單集成
使用IronPDF的 npm 包,即可輕鬆整合到您的Node.js應用程式中。 該 API 文件齊全,可以輕鬆地將 PDF 生成功能整合到您的專案中。
安裝
若要安裝IronPDF NPM 包,請使用下列命令:
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64使用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"接下來,導航到您的專案目錄:
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只能在伺服器端運行,我們需要建立一個 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
}
}現在修改 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許可
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 等。







