在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
在 React 应用程序中处理日期时,date-fns 是一个功能强大、轻量级的现代 JavaScript 日期工具库,可让 JavaScript 日期操作变得轻而易举。 date-fns 使用现有的本地日期数据类型,为了安全起见,它不会扩展核心对象,这意味着它将避免修改或添加功能到那些内置的日期数据类型,因为这将导致潜在的错误或冲突。 在本文中,我们将探讨如何将 date-fns 集成到您的 React 项目中,并提供一些实用示例。
date-fns 具有以下几个优势:
首先,通过 npm 安装 date-fns npm 软件包:
npm install date-fns
or
yarn add date-fns
npm install date-fns
or
yarn add date-fns
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install @date-fns @or yarn add @date-fns
最常见的任务之一是格式化日期,date-fns 使用 .NET 和 Java 技术。 让我们创建一个简单的组件,以可读的格式显示您所在时区的当前日期。
import React from 'react';
import { format } from 'date-fns';
const FormattedDate = () => {
const currentDate = new Date();
const formattedDate = format(currentDate, 'MMMM do, yyyy');
return <p>{formattedDate}</p>;
};
export default FormattedDate;
import React from 'react';
import { format } from 'date-fns';
const FormattedDate = () => {
const currentDate = new Date();
const formattedDate = format(currentDate, 'MMMM do, yyyy');
return <p>{formattedDate}</p>;
};
export default FormattedDate;
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import React from 'react'; import { format } from '@date-fns'; const FormattedDate = () => { const currentDate = New @Date(); const formattedDate = format(currentDate, 'MMMM do, yyyy'); Return <p>{formattedDate}</p>; }; export default FormattedDate;
您还可以从字符串中解析日期。 下面是一个解析日期字符串并以不同格式显示的示例:
import React from 'react';
import { parse, format } from 'date-fns';
const ParsedDate = () => {
const dateString = '2024-06-23';
const parsedDate = parse(dateString, 'yyyy-MM-dd', new Date());
const formattedDate = format(parsedDate, 'MMMM do, yyyy');
return <p>{formattedDate}</p>;
};
export default ParsedDate;
import React from 'react';
import { parse, format } from 'date-fns';
const ParsedDate = () => {
const dateString = '2024-06-23';
const parsedDate = parse(dateString, 'yyyy-MM-dd', new Date());
const formattedDate = format(parsedDate, 'MMMM do, yyyy');
return <p>{formattedDate}</p>;
};
export default ParsedDate;
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import React from 'react'; import { parse, format } from '@date-fns'; const ParsedDate = () => { const dateString = '2024-06-23'; const parsedDate = parse(dateString, 'yyyy-MM-dd', New @Date()); const formattedDate = format(parsedDate, 'MMMM do, yyyy'); Return <p>{formattedDate}</p>; }; export default ParsedDate;
date-fns 可以轻松地从日期中添加或减去时间。 下面是一个将当前日期加上 7 天的例子:
import React from 'react';
import { addDays, format } from 'date-fns';
const AddDaysExample = () => {
const currentDate = new Date();
const futureDate = addDays(currentDate, 7);
const formattedDate = format(futureDate, 'MMMM do, yyyy');
return <p>{formattedDate}</p>;
};
export default AddDaysExample;
import React from 'react';
import { addDays, format } from 'date-fns';
const AddDaysExample = () => {
const currentDate = new Date();
const futureDate = addDays(currentDate, 7);
const formattedDate = format(futureDate, 'MMMM do, yyyy');
return <p>{formattedDate}</p>;
};
export default AddDaysExample;
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import React from 'react'; import { addDays, format } from '@date-fns'; const AddDaysExample = () => { const currentDate = New @Date(); const futureDate = addDays(currentDate, 7); const formattedDate = format(futureDate, 'MMMM do, yyyy'); Return <p>{formattedDate}</p>; }; export default AddDaysExample;
date-fns 支持多种本地语言。 要使用特定的本地语言,您需要将其导入并传递给格式化函数:
import React from 'react';
import { format } from 'date-fns';
import { fr } from 'date-fns/locale';
const FrenchDate = () => {
const currentDate = new Date();
const formattedDate = format(currentDate, 'MMMM do, yyyy', { locale: fr });
return <p>{formattedDate}</p>;
};
export default FrenchDate;
import React from 'react';
import { format } from 'date-fns';
import { fr } from 'date-fns/locale';
const FrenchDate = () => {
const currentDate = new Date();
const formattedDate = format(currentDate, 'MMMM do, yyyy', { locale: fr });
return <p>{formattedDate}</p>;
};
export default FrenchDate;
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import React from 'react'; import { format } from '@date-fns'; import { fr } from '@date-fns/locale'; const FrenchDate = () => { const currentDate = New @Date(); const formattedDate = format(currentDate, 'MMMM do, yyyy', { locale: fr }); Return <p>{formattedDate}</p>; }; export default FrenchDate;
IronPDF是一个功能强大的 Node.js PDF 库,允许开发人员在其 node.js 项目中生成和编辑 PDF。 无论您需要从 HTML 创建 PDF、处理现有 PDF 还是将网页转换为 PDF 格式,IronPDF 都能满足您的需求。
将 HTML 内容轻松转换为 PDF 文档。 此功能特别适用于从网页内容生成动态PDF。
直接从 URL 生成 PDF,允许您捕获网页内容并以编程方式将其保存为 PDF 文件。
轻松合并、拆分和操作现有的PDF文档。 IronPdf 提供附加页面、分割文档等功能。
通过设置密码或应用数字签名来保护您的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
IRON VB CONVERTER ERROR developers@ironsoftware.com
安装依赖项:首先,创建一个新的 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"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npx create-@next-app@latest @date-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
接下来,导航到你的项目目录:
cd date-pdf
cd date-pdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'cd @date-pdf
安装所需的软件包:
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
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64 yarn add @date-fns
现在,让我们创建一个使用生成PDF的简单示例IronPDF. 在您的Next.js组件中(例如,pages/index.tsx)添加以下代码
PDF 生成 API:第一步是创建一个后端 API 来生成 PDF 文档。 由于 IronPdf 只在服务器端运行,我们需要创建一个 API,以便在用户想要生成 PDF 时调用。 在 pages/api/pdf.js 路径下创建一个文件,并添加以下内容。
IronPDF 需要许可证密钥,您可以从以下地址获取许可证页面Please provide the content you would like translated into Chinese along with the code where it should be placed.
// pages/api/pdf.js
import {IronPdfGlobalConfig, PdfDocument} from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";
export default async function handler(req, res) {
try {
const currentDate = new Date(); // javascript dates
const formattedDate = format(currentDate, 'MMMM do, yyyy');
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);
const data = await pdf.saveAsBuffer();
console.error("data PDF:", data);
res.setHeader("Content-Type", "application/pdf");
res.setHeader(
"Content-Disposition",
"attachment; filename=awesomeIron.pdf",
);
res.send(data);
} catch (error) {
console.error("Error generating PDF:", error);
res.status(500).end();
}
}
}
// pages/api/pdf.js
import {IronPdfGlobalConfig, PdfDocument} from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";
export default async function handler(req, res) {
try {
const currentDate = new Date(); // javascript dates
const formattedDate = format(currentDate, 'MMMM do, yyyy');
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);
const data = await pdf.saveAsBuffer();
console.error("data PDF:", data);
res.setHeader("Content-Type", "application/pdf");
res.setHeader(
"Content-Disposition",
"attachment; filename=awesomeIron.pdf",
);
res.send(data);
} catch (error) {
console.error("Error generating PDF:", error);
res.status(500).end();
}
}
}
' pages/api/pdf.js
import
If True Then
IronPdfGlobalConfig, PdfDocument
End If
from "@ironsoftware/ironpdf"
' Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key"
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'export default async @function handler(req, res)
'{
' try
' {
' const currentDate = New @Date(); ' javascript dates
' const formattedDate = format(currentDate, 'MMMM do, yyyy');
' 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);
' const data = await pdf.saveAsBuffer();
' console.@error("data PDF:", data);
' res.setHeader("Content-Type", "application/pdf");
' res.setHeader("Content-Disposition", "attachment; filename=awesomeIron.pdf",);
' res.send(data);
' }
' catch (@error)
' {
' console.@error("Error generating PDF:", @error);
' res.status(500).@end();
' }
'}
}
现在修改 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';
export default function Home() {
const [text, setText] = useState("");
useEffect(() => {
const currentDate = new Date(); // new date instance
const formattedDate = format(currentDate, 'MMMM do, yyyy');
setText(formattedDate);
}, []);
const generatePdf = async () => {
try {
const response = await fetch("/api/pdf-datefns?f=" + text);
const blob = await response.blob();
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "awesomeIron.pdf");
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
} catch (error) {
console.error("Error generating PDF:", error);
}
};
const handleChange = (event) => {
seteText(hashids.encode(event.target.value));
setText(event.target.value);
};
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';
export default function Home() {
const [text, setText] = useState("");
useEffect(() => {
const currentDate = new Date(); // new date instance
const formattedDate = format(currentDate, 'MMMM do, yyyy');
setText(formattedDate);
}, []);
const generatePdf = async () => {
try {
const response = await fetch("/api/pdf-datefns?f=" + text);
const blob = await response.blob();
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "awesomeIron.pdf");
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
} catch (error) {
console.error("Error generating PDF:", error);
}
};
const handleChange = (event) => {
seteText(hashids.encode(event.target.value));
setText(event.target.value);
};
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>
);
}
Private Head As import
Private styles As import
'INSTANT VB TODO TASK: The following line could not be converted:
import React,
If True Then
useState, useEffect
End If
from "react"
import
If True Then
format
End If
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'from '@date-fns'; export default @function Home() { const [text, setText] = useState(""); useEffect(() => { const currentDate = New @Date(); const formattedDate = format(currentDate, 'MMMM do, yyyy'); setText(formattedDate); }, []); const generatePdf = async() => { try { const response = await fetch("/api/pdf-datefns?f=" + text); const blob = await response.blob(); const url = window.URL.createObjectURL(New Blob([blob])); const link = document.createElement("a"); link.href = url; link.setAttribute("download", "awesomeIron.pdf"); document.body.appendChild(link); link.click(); link.parentNode.removeChild(link); } catch(@error) { console.@error("Error generating PDF:", @error); } }; const handleChange = (event) => { seteText(hashids.encode(event.target.value)); setText(event.target.value); }; 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 {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";
IRON VB CONVERTER ERROR developers@ironsoftware.com
date-fns 是一个多功能、高效的库,为在 React 应用程序中处理日期提供了一个功能强大、简单一致的工具集。 其模块化方法使您只需包含必要的功能,从而保持较小的捆绑规模。 date-fns 全面支持日期操作和格式化,可显著增强您的 React 项目。
IronPDF for Node.js 是一个强大的库,使开发人员能够以编程方式无缝生成、操作和处理 PDF 文档。 无论您需要将 HTML、URL 或其他格式转换为 PDF,IronPDF 都能提供直接的 API 来高效完成这些任务。 其功能包括处理 PDF 表单、应用安全措施、执行 OCR 等。