Zum Fußzeileninhalt springen
NODE-HILFE

date-fns NPM (Wie es für Entwickler funktioniert)

Bei der Arbeit mit Datumsangaben in einer React-Anwendung ist date-fns eine leistungsstarke und leichte moderne JavaScript-Datumshilfsbibliothek, die das Manipulieren von JavaScript-Daten erleichtert. date-fns verwendet vorhandene native Datentypen und erweitert keine Kernobjekte aus Sicherheitsgründen, was bedeutet, dass es vermeidet, diesen eingebauten Datentypen Funktionen hinzuzufügen oder zu ändern, was zu potenziellen Fehlern oder Konflikten führen würde. In diesem Artikel werden wir untersuchen, wie date-fns in Ihr React-Projekt integriert werden kann und geben einige praktische Beispiele.

Warum date-fns?

date-fns bietet mehrere Vorteile:

  • Modular: Sie können nur die Funktionen importieren, die Sie benötigen, um die Paketgröße zu reduzieren.
  • Unveränderlich: Es wird mit reinen Funktionen erstellt, sodass diese Funktionen die ursprünglichen Datumsobjekte nicht verändern.
  • Umfassend: Bietet eine breite Palette an Funktionen zur Manipulation und Formatierung von Daten.
  • Internationalisierung: Unterstützt mehrere Sprachen.

Einstieg

Installieren Sie zuerst das npm-Paket date-fns über npm:

npm install date-fns
# or
yarn add date-fns
npm install date-fns
# or
yarn add date-fns
SHELL

Formatierung von Dates

Eine der häufigsten Aufgaben ist die Formatierung von Daten mit date-fns. Lassen Sie uns eine einfache Komponente erstellen, die das aktuelle Datum in Ihrer Zeitzone in einem leserlichen Format anzeigt.

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;
JAVASCRIPT

Ausgabe

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

Parsing von Daten

Sie können auch Daten aus Zeichenfolgen parsen. Hier ist ein Beispiel für das Parsen einer Datumszeichenfolge und deren Anzeige in einem anderen Format:

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;
JAVASCRIPT

Ausgabe

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

Hinzufügen und Subtrahieren von Daten

date-fns macht es einfach, Zeit zu Daten hinzuzufügen oder zu subtrahieren. Hier ist ein Beispiel, wie man dem aktuellen Datum 7 Tage hinzufügt:

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;
JAVASCRIPT

Ausgabe

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

Internationalisierung

date-fns unterstützt mehrere Sprachen. Um eine bestimmte Sprache zu verwenden, müssen Sie sie importieren und der Formatierungsfunktion übergeben:

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;
JAVASCRIPT

Ausgabe

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

Einführung in IronPDF

IronPDF für Node.js ist eine leistungsstarke Node.js PDF-Bibliothek, die es Entwicklern ermöglicht, PDFs in ihren Node.js-Projekten zu erstellen und zu bearbeiten. Egal ob Sie PDFs aus HTML erstellen, bestehende PDFs bearbeiten oder Webseiten in PDF-Format konvertieren müssen, IronPDF bietet umfassende Unterstützung.

date-fns NPM (How It Works For Developers): Abbildung 5 - IronPDF für Node.js: Die Node.js PDF-Bibliothek

Hauptmerkmale

HTML-zu-PDF-Konvertierung

HTML-Inhalte mühelos in PDF-Dokumente konvertieren. Diese Funktion ist besonders nützlich zum Erstellen dynamischer PDFs aus Webinhalten.

URL-zu-PDF-Konvertierung

Erstellen Sie PDFs direkt aus URLs, um den Inhalt von Webseiten zu erfassen und programmgesteuert als PDF-Dateien zu speichern.

PDF-Manipulation

Bestehende PDF-Dokumente leicht zusammenfügen, teilen und manipulieren. IronPDF bietet Funktionen wie das Hinzufügen von Seiten, das Teilen von Dokumenten und mehr.

PDF-Sicherheit

Sichern Sie Ihre PDF-Dokumente, indem Sie sie mit Passwörtern verschlüsseln oder digitale Signaturen anwenden. IronPDF bietet Optionen, um Ihre sensiblen Dokumente vor unbefugtem Zugriff zu schützen.

Hochwertige Ausgabe

Produzieren Sie hochwertige PDF-Dokumente mit präziser Wiedergabe von Text, Bildern und Formatierungen. IronPDF stellt sicher, dass Ihre generierten PDFs die Originalinhalte getreu wiedergeben.

Plattformübergreifende Kompatibilität

IronPDF ist mit verschiedenen Plattformen kompatibel, einschließlich Windows, Linux und macOS, was es für eine Vielzahl von Entwicklungsumgebungen geeignet macht.

Einfache Integration

Integrieren Sie IronPDF problemlos in Ihre Node.js-Anwendungen mithilfe seines npm-Pakets. Die API ist gut dokumentiert, was es einfach macht, PDF-Erstellungsmöglichkeiten in Ihre Projekte zu integrieren.

Installation

Um das NPM-Paket IronPDF zu installieren, verwenden Sie den folgenden Befehl:

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
SHELL

PDF-Dokument mit IronPDF erstellen und date-fns verwenden

Abhängigkeiten installieren: Erstellen Sie zuerst ein neues Next.js-Projekt (falls Sie noch keins haben) mit folgendem Befehl: Siehe hier

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"
SHELL

Navigieren Sie dann zu Ihrem Projektverzeichnis:

cd date-pdf
cd date-pdf
SHELL

Installieren Sie die erforderlichen Pakete:

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
SHELL

Erstellen eines PDFs

Nun, lassen Sie uns ein einfaches Beispiel für die Erstellung eines PDFs mit IronPDF geben. Fügen Sie in Ihrer Next.js-Komponente (z.B. pages/index.tsx) den folgenden Code hinzu:

PDF-Erstellungs-API: Der erste Schritt besteht darin, eine Backend-API zu erstellen, um das PDF-Dokument zu generieren. Da IronPDF nur serverseitig läuft, müssen wir eine API erstellen, die aufgerufen wird, wenn ein Benutzer ein PDF generieren möchte. Erstellen Sie eine Datei im Pfad pages/api/pdf.js und fügen Sie den folgenden Inhalt hinzu.

Ein Lizenzschlüssel ist für IronPDF erforderlich, den Sie auf der Lizenzseite erhalten können und im untenstehenden Codeplatzieren.

// 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
  }
}
JAVASCRIPT

Nun bearbeiten Sie index.js und fügen Sie den folgenden Code hinzu:

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>
  );
}
JAVASCRIPT

Ausgabe

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

PDF

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

IronPDF-Lizenz

IronPDF.

Platzieren Sie den Lizenzschlüssel hier:

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";
JAVASCRIPT

Abschluss

date-fns ist eine vielseitige und effiziente Bibliothek, die ein leistungsstarkes, aber dennoch einfaches und konsistentes Toolset für den Umgang mit Datumsangaben in React-Anwendungen bietet. Durch den modularen Ansatz können Sie nur die notwendigen Funktionen einbinden, wodurch Ihre Paketgröße klein bleibt. Mit umfassender Unterstützung für die Manipulation und Formatierung von Daten kann date-fns Ihre React-Projekte erheblich verbessern.

IronPDF für Node.js ist eine robuste Bibliothek, die es Entwicklern ermöglicht, nahtlos PDF-Dokumente programmgesteuert zu erstellen, zu manipulieren und mit ihnen zu arbeiten. Egal, ob Sie HTML, URLs oder andere Formate in PDFs konvertieren müssen, IronPDF bietet unkomplizierte APIs, um diese Aufgaben effizient zu erledigen. Ihre Fähigkeiten erstrecken sich auf die Handhabung von PDF-Formularen, die Anwendung von Sicherheitsmaßnahmen, das Durchführen von OCR und mehr.

Darrius Serrant
Full-Stack-Software-Ingenieur (WebOps)

Darrius Serrant hat einen Bachelor-Abschluss in Informatik von der University of Miami und arbeitet als Full-Stack-WebOps-Marketing-Ingenieur bei Iron Software. Seit seiner Jugend vom Programmieren angezogen, sah er die Informatik als sowohl mysteriös als auch zugänglich, was es zum perfekten Medium für Kreativität und Problemlösung ...

Weiterlesen