How to format a date as a relative time (e.g., "2 hours ago") using JavaScript?

You can format a date as a relative time using JavaScript by calculating the time difference between the current date and the given date, and then converting it into a relative format. Here's an example:

function formatRelativeTime(date) { const currentDate = new Date(); const timeDifference = currentDate - date; // Convert time difference into seconds const seconds = Math.floor(timeDifference / 1000); if (seconds < 60) { return `${seconds} seconds ago`; } // Convert time difference into minutes const minutes = Math.floor(timeDifference / (1000 * 60)); if (minutes < 60) { return `${minutes} minutes ago`; } // Convert time difference into hours const hours = Math.floor(timeDifference / (1000 * 60 * 60)); if (hours < 24) { return `${hours} hours ago`; } // Convert time difference into days const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24)); if (days < 7) { return `${days} days ago`; } // Convert time difference into weeks const weeks = Math.floor(timeDifference / (1000 * 60 * 60 * 24 * 7)); return `${weeks} weeks ago`; } // Example usage const date = new Date('2021-10-10T08:00:00'); const relativeTime = formatRelativeTime(date); console.log(relativeTime); // Output: "2 hours ago"

In the example above, the formatRelativeTime function takes a date parameter and calculates the time difference between the current date (currentDate) and the given date. It then converts the time difference into seconds, minutes, hours, days, or weeks, depending on the magnitude of the time difference.

You can adjust the conditions and formatting as per your requirements.