Back to home page

JavaScript Relative Time

Generate human-readable relative timestamps

Checksum (SHA-256)4d29b3d2cca3e982044eac0fe6d2d37c6b6ad5c9b139ae94a4c2ffb45255ab3a
Namekiwi.mia.0021
Version25.1.0
Stage90.92 Archived
Released2025-06-30 00:00:00
Next version25.1.1
Previous version25.0.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.0

  • Renamed the function to getRelativeTime.
  • Added short parameter to use short forms for time units.
  • Added precision parameter to control the level of precision in the output.
  • Added hideTemporalIndicator parameter to omit the "ago" or "from now" suffix.
 Show 25.0.0  Show timeline Show 25.1.1