Concise ISO 8601 Date Formatter and Parser for JavaScript – isoformat

Concise ISO 8601 Date Formatter and Parser for JavaScript – isoformat
Concise ISO 8601 Date Formatter and Parser for JavaScript – isoformat
isoformat is a lightweight JavaScript utility library that formats and parses ISO 8601 dates with readability and brevity.

It enables you to generate the shortest valid ISO 8601 representation for any given date. This is ideal for data interchange formats like CSV files where 2001-01-01

is more readable than 2001-01-01T00:00:00.000Z.

In addition, the library handles both formatting dates to strings and parsing strings back to Date objects with full support for multiple ISO 8601 variants.

Features:

  • Concise output formats: Returns the shortest valid ISO 8601 string (date-only when time is midnight UTC, omits seconds when zero).
  • Full parsing support: Accepts 10 different ISO 8601 format variations including timezone offsets.
  • Zero dependencies: Pure JavaScript implementation with no external requirements.
  • Minimal footprint: Extremely small library size with just two core functions.
  • Fallback handling: Built-in support for custom fallback values or functions when dates are invalid.
  • UTC-based operations: All formatting and parsing operations use UTC to avoid timezone confusion.
  • Extended year support: Handles dates outside the standard 0000-9999 range with +YYYYYY and -YYYYYY notation.

Use Cases:

  • CSV data export: Generate human-readable date columns in CSV files without the full timestamp clutter.
  • API response formatting: Return cleaner date strings in REST API responses where full timestamps are unnecessary.
  • Database timestamp storage: Store dates in a readable text format that’s still ISO 8601 compliant for sorting and querying.
  • Data migration scripts: Parse various ISO 8601 formats from legacy systems that use different datetime conventions.

How To Use It:

1. Install the library via npm:

npm install isoformat

2. Import the functions and start formatting or parsing dates:

import {format, parse} from "isoformat";

// Format a Date object to the shortest ISO 8601 string
const date1 = new Date(Date.UTC(2001, 0, 1));
console.log(format(date1)); // "2001-01-01"

// Format a datetime with time components
const date2 = new Date(Date.UTC(2020, 0, 1, 12, 23));
console.log(format(date2)); // "2020-01-01T12:23Z"

// Parse an ISO date string back to a Date object
const parsed1 = parse("2001-01-01"); 
// Returns: new Date(Date.UTC(2001, 0, 1))

const parsed2 = parse("2020-01-01T12:23Z"); 
// Returns: new Date(Date.UTC(2020, 0, 1, 12, 23))

3. Using fallback values for invalid dates:

// Provide a default fallback value
const result1 = format(new Date("invalid"), "N/A");
console.log(result1); // "N/A"

// Use a function to generate fallback values dynamically
const result2 = format(
  new Date("invalid"), 
  (date) => `Error formatting: ${date}` // Custom fallback function
);

// Same fallback pattern works for parsing
const parsed = parse("not-a-date", null); // Returns null instead of undefined

4. Handling milliseconds and seconds:

// The library automatically includes only necessary precision
const withMillis = new Date(Date.UTC(2020, 5, 15, 9, 30, 45, 123));
console.log(format(withMillis)); 
// "2020-06-15T09:30:45.123Z" - includes milliseconds

const withSeconds = new Date(Date.UTC(2020, 5, 15, 9, 30, 45));
console.log(format(withSeconds)); 
// "2020-06-15T09:30:45Z" - includes seconds, omits milliseconds

const withMinutes = new Date(Date.UTC(2020, 5, 15, 9, 30));
console.log(format(withMinutes)); 
// "2020-06-15T09:30Z" - omits seconds when zero

5. Parsing different ISO 8601 formats:

// The parser accepts various ISO 8601 representations
parse("2020");                        // Year only
parse("2020-06");                     // Year and month
parse("2020-06-15");                  // Full date
parse("2020-06-15T09:30");            // Date with time (no timezone = local)
parse("2020-06-15T09:30Z");           // Date with time in UTC
parse("2020-06-15T09:30:45");         // Date with seconds
parse("2020-06-15T09:30:45.123Z");    // Date with milliseconds
parse("2020-06-15T09:30:45+05:30");   // Date with timezone offset
parse("2020-06-15T09:30:45+0530");    // Date with compact timezone offset

API Methods:

format(date, fallback)

Formats a Date object or timestamp to the shortest equivalent ISO 8601 UTC string.

  • Parameters:
    • date (Date | number): A Date instance or milliseconds since UNIX epoch.
    • fallback (any | function, optional): Value to return if the date is invalid. If a function, it will be invoked with the invalid date as an argument. Defaults to undefined.
  • Returns: (string | any): An ISO 8601 formatted string, or the fallback value if the date is invalid.
  • Output formats:
    • YYYY-MM-DD – Date only (when time is midnight UTC)
    • YYYY-MM-DDTHH:MMZ – Date with hours and minutes (when seconds are zero)
    • YYYY-MM-DDTHH:MM:SSZ – Date with hours, minutes, and seconds (when milliseconds are zero)
    • YYYY-MM-DDTHH:MM:SS.MMMZ – Date with full precision including milliseconds
    • Extended years: +YYYYYY or -YYYYYY for dates outside 0000-9999 range

parse(string, fallback)

Parses an ISO 8601 date or datetime string into a Date instance.

  • Parameters:
    • string (string): An ISO 8601 formatted date or datetime string.
    • fallback (any | function, optional): Value to return if the string is not a valid ISO 8601 format. If a function, it will be invoked with the invalid string as an argument. Defaults to undefined.
  • Returns: (Date | any): A Date instance, or the fallback value if the string is invalid.
  • Accepted formats:
    • YYYY – Year only
    • YYYY-MM – Year and month
    • YYYY-MM-DD – Full date
    • YYYY-MM-DDTHH:MM – Date with time (no timezone)
    • YYYY-MM-DDTHH:MMZ – Date with time in UTC
    • YYYY-MM-DDTHH:MM:SS – Date with seconds (no timezone)
    • YYYY-MM-DDTHH:MM:SSZ – Date with seconds in UTC
    • YYYY-MM-DDTHH:MM:SS.MMM – Date with milliseconds (no timezone)
    • YYYY-MM-DDTHH:MM:SS.MMMZ – Date with milliseconds in UTC
    • Extended years: +YYYYYY or -YYYYYY
    • Timezone formats: Z (UTC), +HH:MM, -HH:MM, +HHMM, -HHMM

Alternatives

  • date-fns: Provides formatISO() and parseISO() functions with extensive date manipulation utilities, but adds significant bundle size for projects that only need basic ISO formatting.
  • Day.js: Offers ISO 8601 formatting through plugins with a chainable API, though it requires loading the entire library even for simple date operations.
  • Date Format: Browse more open-source date format libraries at CSSScript.com.

Changelog:

12/02/2025

  • Update the Doc

The post Concise ISO 8601 Date Formatter and Parser for JavaScript – isoformat appeared first on CSS Script.


Discover more from RSS Feeds Cloud

Subscribe to get the latest posts sent to your email.

Discover more from RSS Feeds Cloud

Subscribe now to keep reading and get access to the full archive.

Continue reading