Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
When working with dates in a React application, date-fns is a powerful and lightweight modern JavaScript date utility library that makes manipulating JavaScript dates a breeze. date-fns uses existing native dates data types, it doesn’t extend core objects for safety’s sake, meaning it will avoid modifying or adding functionalities to those built in date data types, which would lead to potential errors or conflicts. In this article, we’ll explore how to integrate date-fns into your React project and provide some practical examples.
date-fns offers several advantages:
First, install date-fns npm package via npm:
npm install date-fns
or
yarn add date-fns
One of the most common tasks is formatting dates, date-fns uses . Let’s create a simple component that displays the current date in your time zone in a readable format.
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;
You can also parse dates from strings. Here’s an example of parsing a date string and displaying it in a different format:
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 makes it easy to add or subtract time from dates. Here’s an example of adding 7 days to the current date:
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 supports multiple locales. To use a specific local, you need to import it and pass it to the formatting function:
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 for Node.js is a powerful Node.js PDF library that allows developers to generate and edit PDFs in their node.js projects. Whether you need to create PDFs from HTML, manipulate existing PDFs, or convert web pages to PDF format, IronPDF has got you covered.
Convert HTML content into PDF documents effortlessly. This feature is particularly useful for generating dynamic PDFs from web content.
Generate PDFs directly from URLs, allowing you to capture the content of web pages and save them as PDF files programmatically.
Merge, split, and manipulate existing PDF documents with ease. IronPDF provides functionalities such as appending pages, splitting documents, and more.
Secure your PDF documents by encrypting them with passwords or applying digital signatures. IronPDF offers options to protect your sensitive documents from unauthorized access.
Produce high-quality PDF documents with precise rendering of text, images, and formatting. IronPDF ensures that your generated PDFs maintain fidelity to the original content.
IronPDF is compatible with various platforms, including Windows, Linux, and macOS, making it suitable for a wide range of development environments.
Easily integrate IronPDF into your Node.js applications using its npm package. The API is well-documented, making it straightforward to incorporate PDF generation capabilities into your projects.
To install the IronPDF NPM package, use the following command:
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
Install Dependencies: First, create a new Next.js project (if you haven’t already) using the following command: Refer here
npx create-next-app@latest date-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
Next, navigate to your project directory:
cd date-pdf
Install the required packages:
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add date-fns
Now, let’s create a simple example of generating a PDF using IronPDF. In your Next.js component (e.g., pages/index.tsx), add the following code:
PDF Generation API: First step is to create a backend API to generate the PDF document. Since IronPDF only runs server side, we need to create an API to call when a user wants to generate PDF. Create a file in path pages/api/pdf.js and add the below contents.
License key is required for IronPDF , you can get it from the license page and place it in the below code.
// 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();
}
}
}
Now modify the index.js and add below code
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>
);
}
Place the License Key here:
import {IronPdfGlobalConfig, PdfDocument} from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
date-fns is a versatile and efficient library that provides a powerful, yet simple and consistent toolset for handling dates in React applications. Its modular approach allows you to include only what you need in terms of necessary functions, keeping your bundle size small. With comprehensive support for date manipulation and formatting, date-fns can significantly enhance your React projects.
IronPDF for Node.js is a robust library that enables developers to seamlessly generate, manipulate, and work with PDF documents programmatically. Whether you need to convert HTML, URLs, or other formats into PDFs, IronPDF offers straightforward APIs to accomplish these tasks efficiently. Its capabilities extend to handling PDF forms, applying security measures, performing OCR, and more.
9 .NET API products for your office documents