Format Relative Time (time ago)
Format Relative Time (time ago) is a reusable JavaScript snippet. Converts a date to a human-readable relative time string like "2 hours ago" or "in 3 days". The full implementation: function timeAgo(date) { const now = Date.now() const diff = date - now const seconds = Math.abs(diff) / 1000 const units = [ { name: 'year', seconds: 31536000 }, { name: 'month', seconds: 2592000 }, { name: 'week', seconds: 604800 }, { name: 'day', seconds: 86400 }, { name: 'hour', seconds: 3600 }, { name: 'minute', seconds: 60 }, { name: 'second', seconds: 1 }, ] for (const unit of units) { if (seconds >= unit.seconds) { const count =… This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.