▲reactivite
/packages/docs/courses/cli/skillpool/promaster/contact
all docs

$ npm view @ubuligan/date-formatter

Utility

@ubuligan/date-formatter

A lightweight TypeScript utility for safely formatting Date, string, or Dayjs values with flexible input support and custom output formats.

npm versiondownloads
npm github
$ npm install @ubuligan/date-formatter

@ubuligan/date-formatter#

npm version TypeScript License: MIT

A lightweight, zero-dependency TypeScript utility for safely formatting dates with flexible input support and custom output formats.

✨ Features#

  • 🚀 Zero dependencies - No external libraries required
  • 📅 Flexible input formats - Supports Date objects, ISO strings, and common date formats
  • 🎨 Custom output formatting - Define your own format patterns
  • 🛡️ Type-safe - Full TypeScript support with proper type definitions
  • 🔄 Robust parsing - Handles various date formats automatically
  • 💪 Error handling - Returns empty string for invalid dates instead of throwing

📦 Installation#

npm install @ubuligan/date-formatter
yarn add @ubuligan/date-formatter
pnpm add @ubuligan/date-formatter

🚀 Quick Start#

import { formatDateForDisplay } from "@ubuligan/date-formatter";

// Basic usage with default format (YYYY-MM-DD)
const formatted = formatDateForDisplay("2025-10-13");
console.log(formatted); // "2025-10-13"

// Custom format
const customFormat = formatDateForDisplay(
  "2025-10-13T15:45:30Z",
  "DD/MM/YYYY HH:mm"
);
console.log(customFormat); // "13/10/2025 15:45"

📖 API Reference#

formatDateForDisplay(dateValue, format?)#

Formats a date value into a string using the specified format pattern.

Parameters#

  • dateValue (string | Date | null | undefined) - The date to format
  • format (string, optional) - The output format pattern (default: "YYYY-MM-DD")

Returns#

  • string - The formatted date string, or empty string if the input is invalid

Format Tokens#

TokenDescriptionExample
YYYY4-digit year2025
MM2-digit month (01-12)10
DD2-digit day (01-31)13
HH2-digit hour (00-23)15
mm2-digit minute (00-59)45
ss2-digit second (00-59)30

📝 Usage Examples#

Basic Date Formatting#

import { formatDateForDisplay } from "@ubuligan/date-formatter";

// Date object
const date = new Date("2025-10-13T15:45:30Z");
console.log(formatDateForDisplay(date)); // "2025-10-13"

// ISO string
console.log(formatDateForDisplay("2025-10-13T15:45:30Z")); // "2025-10-13"

// Custom format
console.log(formatDateForDisplay(date, "DD/MM/YYYY")); // "13/10/2025"

Supported Input Formats#

// ISO format
formatDateForDisplay("2025-10-13T15:45:30Z", "YYYY-MM-DD HH:mm:ss");
// → "2025-10-13 15:45:30"

// European format (DD/MM/YYYY)
formatDateForDisplay("13/10/2025", "YYYY-MM-DD");
// → "2025-10-13"

// Dot notation with time
formatDateForDisplay("13.10.2025 09:20", "DD.MM.YYYY HH:mm");
// → "13.10.2025 09:20"

// American format (MM-DD-YYYY)
formatDateForDisplay("10-13-2025 23:59", "DD/MM/YYYY HH:mm:ss");
// → "13/10/2025 23:59:00"

// Current date
formatDateForDisplay(new Date(), "YYYY-MM-DD HH:mm");
// → "2025-10-13 14:40" (current time)

Custom Format Patterns#

// Different separators
formatDateForDisplay("2025-10-13", "DD.MM.YYYY"); // "13.10.2025"
formatDateForDisplay("2025-10-13", "DD-MM-YYYY"); // "13-10-2025"
formatDateForDisplay("2025-10-13", "MM/DD/YYYY"); // "10/13/2025"

// With time
formatDateForDisplay("2025-10-13T15:45:30", "YYYY-MM-DD HH:mm:ss"); // "2025-10-13 15:45:30"
formatDateForDisplay("2025-10-13T15:45:30", "DD/MM/YYYY HH:mm"); // "13/10/2025 15:45"

// Custom text
formatDateForDisplay("2025-10-13", "DD of MM, YYYY"); // "13 of 10, 2025"
formatDateForDisplay("2025-10-13T15:45", "YYYY-MM-DD at HH:mm"); // "2025-10-13 at 15:45"

Error Handling#

// Invalid inputs return empty string
console.log(formatDateForDisplay(null)); // ""
console.log(formatDateForDisplay(undefined)); // ""
console.log(formatDateForDisplay("")); // ""
console.log(formatDateForDisplay("invalid-date")); // ""

// Safe to use in templates
const userDate = getUserDate(); // might be null/undefined
const display = formatDateForDisplay(userDate) || "No date provided";

🎯 Real-World Use Cases#

📊 Data Tables & Lists#

Perfect for displaying dates in tables, lists, and data grids:

import { formatDateForDisplay } from "@ubuligan/date-formatter";

// User list with registration dates
const users = [
  { name: "John", registeredAt: "2025-01-15T10:30:00Z" },
  { name: "Jane", registeredAt: "2025-02-20T14:45:30Z" },
  { name: "Bob", registeredAt: null },
];

// Format for display
const userList = users.map((user) => ({
  ...user,
  registrationDate:
    formatDateForDisplay(user.registeredAt, "DD/MM/YYYY") || "Not registered",
}));

console.log(userList);
// [
//   { name: 'John', registrationDate: '15/01/2025' },
//   { name: 'Jane', registrationDate: '20/02/2025' },
//   { name: 'Bob', registrationDate: 'Not registered' }
// ]

🌐 API Response Formatting#

Handle various date formats from different APIs:

// API might return different date formats
const apiResponse = {
  createdAt: "2025-10-13T15:45:30.123Z", // ISO with milliseconds
  updatedAt: "13/10/2025", // European format
  publishedAt: "10-13-2025 15:45", // American format
  expiredAt: null, // Null value
};

// Normalize all dates to consistent format
const normalizedData = {
  created: formatDateForDisplay(apiResponse.createdAt, "YYYY-MM-DD HH:mm"),
  updated: formatDateForDisplay(apiResponse.updatedAt, "YYYY-MM-DD"),
  published: formatDateForDisplay(apiResponse.publishedAt, "DD.MM.YYYY HH:mm"),
  expired: formatDateForDisplay(apiResponse.expiredAt) || "Never expires",
};

console.log(normalizedData);
// {
//   created: '2025-10-13 15:45',
//   updated: '2025-10-13',
//   published: '13.10.2025 15:45',
//   expired: 'Never expires'
// }

📱 React Components#

Seamless integration with React applications:

import React from "react";
import { formatDateForDisplay } from "@ubuligan/date-formatter";

interface BlogPostProps {
  title: string;
  content: string;
  publishedAt: string | Date | null;
  updatedAt?: string | Date | null;
}

const BlogPost: React.FC<BlogPostProps> = ({
  title,
  content,
  publishedAt,
  updatedAt,
}) => {
  return (
    <article>
      <h1>{title}</h1>
      <div className="meta">
        <span>
          Published:{" "}
          {formatDateForDisplay(publishedAt, "DD MMM YYYY") || "Draft"}
        </span>
        {updatedAt && (
          <span>
            Updated: {formatDateForDisplay(updatedAt, "DD MMM YYYY HH:mm")}
          </span>
        )}
      </div>
      <div>{content}</div>
    </article>
  );
};

// Usage
<BlogPost
  title="My Blog Post"
  content="Content here..."
  publishedAt="2025-10-13T15:45:30Z"
  updatedAt="2025-10-14T09:30:00Z"
/>;

📋 Form Validation & Display#

Handle user input and display formatted dates:

// Form handling with date validation
function handleDateInput(userInput: string): {
  isValid: boolean;
  formatted: string;
} {
  const formatted = formatDateForDisplay(userInput, "DD/MM/YYYY");

  return {
    isValid: formatted !== "",
    formatted: formatted || "Invalid date format",
  };
}

// Examples
console.log(handleDateInput("2025-10-13")); // { isValid: true, formatted: '13/10/2025' }
console.log(handleDateInput("13/10/2025")); // { isValid: true, formatted: '13/10/2025' }
console.log(handleDateInput("invalid")); // { isValid: false, formatted: 'Invalid date format' }

📈 Analytics & Reporting#

Format dates for charts, reports, and analytics:

// Sales report with date grouping
const salesData = [
  { date: "2025-10-01T00:00:00Z", amount: 1200 },
  { date: "2025-10-02T00:00:00Z", amount: 1500 },
  { date: "2025-10-03T00:00:00Z", amount: 980 },
];

// Format for chart labels
const chartData = salesData.map((item) => ({
  label: formatDateForDisplay(item.date, "DD MMM"), // "01 Oct", "02 Oct", etc.
  value: item.amount,
}));

// Format for detailed report
const reportData = salesData.map((item) => ({
  date: formatDateForDisplay(item.date, "DD/MM/YYYY"),
  amount: `$${item.amount}`,
  timestamp: formatDateForDisplay(item.date, "YYYY-MM-DD HH:mm:ss"),
}));

🔄 Database Integration#

Handle dates from database queries:

// MongoDB/SQL query results
const dbResults = [
  { _id: "1", created_at: new Date("2025-10-13T15:45:30Z") },
  { _id: "2", created_at: "2025-10-14 10:30:00" }, // SQL datetime
  { _id: "3", created_at: null }, // NULL value
];

// Format for API response
const apiResponse = dbResults.map((record) => ({
  id: record._id,
  createdAt: formatDateForDisplay(record.created_at, "YYYY-MM-DD HH:mm:ss"),
  createdAtISO: record.created_at
    ? new Date(record.created_at).toISOString()
    : null,
}));

📧 Email Templates & Notifications#

Generate human-readable dates for communications:

// Email notification
function generateWelcomeEmail(user: { name: string; joinedAt: string }) {
  const joinDate = formatDateForDisplay(user.joinedAt, "DD MMMM YYYY");

  return `
    Welcome ${user.name}!

    You joined our platform on ${joinDate}.
    We're excited to have you aboard!
  `;
}

// SMS notification
function generateReminderSMS(appointment: { datetime: string; type: string }) {
  const date = formatDateForDisplay(appointment.datetime, "DD/MM/YYYY");
  const time = formatDateForDisplay(appointment.datetime, "HH:mm");

  return `Reminder: ${appointment.type} appointment on ${date} at ${time}`;
}

🌍 Internationalization Support#

Adapt to different regional date formats:

// Different regional preferences
const dateValue = "2025-10-13T15:45:30Z";

const formats = {
  US: formatDateForDisplay(dateValue, "MM/DD/YYYY HH:mm"), // "10/13/2025 15:45"
  EU: formatDateForDisplay(dateValue, "DD/MM/YYYY HH:mm"), // "13/10/2025 15:45"
  ISO: formatDateForDisplay(dateValue, "YYYY-MM-DD HH:mm"), // "2025-10-13 15:45"
  German: formatDateForDisplay(dateValue, "DD.MM.YYYY HH:mm"), // "13.10.2025 15:45"
  Compact: formatDateForDisplay(dateValue, "DD-MM-YY"), // "13-10-25"
};

// Dynamic formatting based on user locale
function formatForLocale(date: string | Date, locale: string): string {
  const formats: Record<string, string> = {
    "en-US": "MM/DD/YYYY",
    "en-GB": "DD/MM/YYYY",
    "de-DE": "DD.MM.YYYY",
    "fr-FR": "DD/MM/YYYY",
    default: "YYYY-MM-DD",
  };

  return formatDateForDisplay(date, formats[locale] || formats.default);
}

🔧 TypeScript Support#

This package includes full TypeScript definitions:

import { formatDateForDisplay } from "@ubuligan/date-formatter";

// Type-safe usage
const result: string = formatDateForDisplay(new Date(), "YYYY-MM-DD");

// Function signature
declare function formatDateForDisplay(
  dateValue: string | Date | null | undefined,
  format?: string
): string;

🧪 Testing#

Run the included test examples:

npm run build
npm test

🤝 Contributing#

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License#

This project is licensed under the MIT License - see the LICENSE file for details.

👨‍💻 Author#

Javid Salimov

  • GitHub: @jsznpm

🔗 Links#

  • npm package
  • GitHub repository
  • Issues

Made with ❤️ by Javid Salimov

  • home
  • packages
  • skillpool
  • docs
  • cli
▲reactivite

// The fastest way to scaffold production-ready React apps. Built by developers, for developers.

$ npm create reactivite@latest

resources/

  • └─ documentation
  • └─ packages
  • └─ cli
  • └─ courses
  • └─ markdown
  • └─ diff
  • └─ run
  • └─ radio
  • └─ tv
  • └─ games
  • └─ about
  • └─ contact

community/

  • └─ github

© 2026 reactivite — all rights reserved