Tiny JS Library for Human-Readable Timestamps – little-timestamp

Category: Date & Time , Javascript | June 9, 2025
Authormsmps
Last UpdateJune 9, 2025
LicenseMIT
Views52 views
Tiny JS Library for Human-Readable Timestamps – little-timestamp

little-timestamp is a tiny timestamp formatting library (TypeScript) that transforms JavaScript Date objects into clean, human-readable strings like “2h ago” or “Jun 15”.

The library has the ability to make smart decisions about when to show relative time versus absolute dates. For recent timestamps, it displays relative formats like “3m ago” or “5h from now.” For older dates, it switches to month-day format, adding the year only when necessary.

  • Zero dependencies with tiny bundle size
  • Handles both past and future timestamps
  • Automatic locale detection with override options
  • TypeScript support with full type definitions
  • Opinionated formatting that switches between relative and absolute display
  • Custom reference date support for testing scenarios
  • Cross-browser compatibility including server-side rendering

See Also:

How to use it:

1. Install little-timestamp and import ‘formatTimestamp’ into your JS.

# Yarn
$ yarn add little-timestamp
# NPM
$ npm install little-timestamp
# PNPM
$ pnpm install little-timestamp
import { formatTimestamp } from "little-timestamp";

2. Basic Usage.

// A timestamp from 6 hours ago
const timestamp = new Date(Date.now() - 6 * 60 * 60 * 1000);
console.log(formatTimestamp(timestamp)); // Outputs: "6h ago"
// A timestamp from a different day
const olderTimestamp = new Date("2025-06-01T10:00:00.000Z");
console.log(formatTimestamp(olderTimestamp)); // Outputs: "Jun 1"

3. The library accepts an options object with two parameters:

  • locale (string): Override the default browser locale for date formatting. Defaults to navigator.language or “en-US” in server environments
  • today (Date): Specify a custom reference date instead of the current time. Useful for testing or calculating relative times from a specific point
formatTimestamp(timestamp, {
  locale: "es-ES", // Use Spanish locale
  today: new Date("2025-06-02T12:00:00.000Z") // Custom reference date
});

Performance Considerations

The library performs minimal calculations using basic Date methods and Math.floor() operations. The most expensive operation is the Intl.DateTimeFormat call for absolute dates, which only happens for timestamps older than 24 hours. For high-frequency updates, consider memoizing results or batching timestamp calculations.

You Might Be Interested In:


Leave a Reply