JavaScript/TypeScript: print relative times with no dependencies. e.g. "3 minutes ago", "1 week ago"
✓ Published0🌍 Public
TTommasoAmici
Last edited Jun 12, 2022
Created on May 19, 2022
This example demonstrates how to format relative time strings like “3 minutes ago” or “1 week ago” using the native JavaScript `Intl.RelativeTimeFormat` API. It defines a `formatDate` function that calculates the time difference between a given `Date` and the current moment, then selects the appropriate unit—seconds, minutes, hours, days, weeks, months, or years—based on the elapsed duration. The code uses no external dependencies, relying solely on TypeScript and the built-in `Intl.RelativeTimeFormat` with `numeric: "auto"` for human-friendly output.
AI-generated description