Back to home page

JavaScript Relative Time

Generate human-readable relative timestamps

Checksum (SHA-256)acb47ca2cb7adc4ab336c8358f54c47382e1cbad32709a3193ed75bdb1c2c586
Namekiwi.mia.0021
Version25.1.1
Stage60.50 Published
Released2025-07-01 00:00:00
Previous version25.1.0

A small (tiny) JavaScript project to generate a customizable and human-readable string to represent the relative time between two points in time.

A small JavaScript function used to display relative time in a human-readable format. Supports dates in the past, present, and future, with options for excluding certain time units and setting precision levels. The function can also return short forms for time units if specified.

/**
 * Returns a human-readable string representing the relative time between a target and a reference date.
 * @param target The target date in the future, past, or present.
 * @param excludedUnits An array of time units to exclude from the output (e.g. ["year", "month"]).
 * @param reference The reference date to compare against, usually the current date.
 * @param short If true, uses short forms for time units (e.g. "y" for years).
 * @param precision The level of precision for the output (if the desired precision level is reached and is not zero, the following units won't be included in the ouput).
 * @param hideTemporalIndicator If true, the "ago" or "from now" suffix is omitted.
 * @returns A string representing the relative time (e.g. "2 days ago", "3 weeks from now").
 * @throws Will throw an error if the target or reference date is invalid.
 */

Examples

Get the relative time from 2025-06-330 and 1979-01-01:

getRelativeTime("1979-01-01", [], "2025-06-30");

Outputs: 46 years, 5 months, 2 weeks, 2 days, 17 hours, 2 minutes and 24 seconds ago


Get the relative time from 2025-06-30 and 2026-04-29, excluding weeks:

getRelativeTime("2026-04-29", ["week"], "2025-06-30");

Outputs: 9 months, 28 days, 21 hours, 4 minutes and 19 seconds from now


Get the relative time from 2025-06-30 and 2000-01-01, in years and using the short form:

getRelativeTime("2000-01-01", [], "2025-06-30", true, "year");

Outputs: 25 y ago

Changes in 25.1.1

  • Fixed hideTemporalIndicator parameter so it actually does something haha
 Show 25.1.0  Show timeline Show