NODE HELP

date-fns NPM (How It Works For Developers)

Published October 24, 2024
Share:

Introduction

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.

Why date-fns?

date-fns offers several advantages:

  • Modular: You can import only the functions you need, reducing bundle size.
  • Immutable: It's built using pure functions and so these functions do not mutate the original date objects.
  • Comprehensive: Provides a wide range of functions for date manipulation and formatting.
  • Internationalization: Supports multiple locales.

Getting Started

First, install date-fns npm package via 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
VB   C#

Formatting Dates

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;
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;
VB   C#

Output

date-fns NPM (How It Works For Developers): Figure 1

Parsing Dates

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;
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;
VB   C#

Output

date-fns NPM (How It Works For Developers): Figure 2

Adding and Subtracting Dates

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;
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;
VB   C#

Output

date-fns NPM (How It Works For Developers): Figure 3

Internationalization

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;
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;
VB   C#

Output

date-fns NPM (How It Works For Developers): Figure 4

Introducing IronPDF

IronPDF 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.

date-fns NPM (How It Works For Developers): Figure 5 - IronPDF for Node.js: The Node.js PDF Library

Key Features

HTML to PDF Conversion

Convert HTML content into PDF documents effortlessly. This feature is particularly useful for generating dynamic PDFs from web content.

URL to PDF Conversion

Generate PDFs directly from URLs, allowing you to capture the content of web pages and save them as PDF files programmatically.

PDF Manipulation

Merge, split, and manipulate existing PDF documents with ease. IronPDF provides functionalities such as appending pages, splitting documents, and more.

PDF Security

Secure your PDF documents by encrypting them with passwords or applying digital signatures. IronPDF offers options to protect your sensitive documents from unauthorized access.

High-Quality Output

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.

Cross-Platform Compatibility

IronPDF is compatible with various platforms, including Windows, Linux, and macOS, making it suitable for a wide range of development environments.

Simple Integration

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.

Installation

To install the IronPDF NPM package, use the following command:

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
VB   C#

Generate PDF Document Using IronPDF and Use Date-Fns

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"
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"
VB   C#

Next, navigate to your project directory:

cd date-pdf
cd date-pdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'cd @date-pdf
VB   C#

Install the required packages:

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
VB   C#

Create a PDF

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();
  }
}
}
// 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();
'  }
'}
}
VB   C#

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>
  );
}
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>); }
VB   C#

Output

date-fns NPM (How It Works For Developers): Figure 6

PDF

date-fns NPM (How It Works For Developers): Figure 7

IronPDF License

IronPDF.

Place the License Key here:

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
VB   C#

Conclusion

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.

< PREVIOUS
memcached npm (How It Works For Developers)
NEXT >
express validator npm (How It Works For Developers)

Ready to get started? Version: 2024.9 just released

Free npm Install View Licenses >