How to Show Customized Relative Time with JavaScript

Learn how to create a JavaScript function to display relative time (like "5min ago" or "2y ago") by calculating the difference between the current date and an input date, converting it into various time units (seconds, minutes, hours, days, weeks, months, years), and returning the most appropriate unit as a string.

Algogenz logo

4m · 5min read

Hey everyone! Today, I want to share a neat trick on how to display relative time in a customized format using JavaScript. If you've ever wanted to show time differences in a user-friendly way, like "5min" or "2y," this post is for you. I'll walk you through the process step-by-step, explaining every part of the code so you can understand how it works and apply it in your projects.


Creating the Function

Let's start by creating a function called formatDate. This function will take a date string as input and return a relative time string.

export const formatDate = (dateString) => {
    const now = new Date();
    const date = new Date(dateString);
    const diff = now - date;
    const seconds = Math.floor(diff / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    const weeks = Math.floor(days / 7);
    const months = Math.floor(days / 30);
    const years = Math.floor(days / 365);

    if (seconds < 60) {
        return `${seconds}s`;
    } else if (minutes < 60) {
        return `${minutes}min`;
    } else if (hours < 24) {
        return `${hours}h`;
    } else if (days < 7) {
        return `${days}d`;
    } else if (weeks < 4) {
        return `${weeks}w`;
    } else if (months < 12) {
        return `${months}m`;
    } else {
        return `${years}y`;
    }
};

Breaking Down the Code

Let's dive into the code and break it down step-by-step to understand how it works.


Getting the Current Date and Time

const now = new Date();
  • This line gets the current date and time.
  • new Date() creates a Date object representing the current moment in time.
  • This Date object is essential because it provides a reference point from which we calculate the difference with the input date.


Parsing the Input Date String

const date = new Date(dateString);
  • This line parses the input date string to create a Date object.
  • The dateString parameter is the date and time we want to compare against the current date and time.
  • new Date(dateString) creates a Date object from the input string, allowing us to perform date calculations.
  • It's important to ensure that dateString is in a valid format (e.g., ISO 8601) to initialize the Date object correctly.


Calculating the Difference

const diff = now - date;
  • Here, we calculate the difference in milliseconds between the current date (now) and the input date (date).
  • Subtracting one Date object from another gives us the difference in milliseconds.
  • This difference is the foundation for all subsequent calculations, as it represents the total elapsed time.


Converting the Difference to Different Units

Next, we need to convert this difference into more understandable units: seconds, minutes, hours, days, weeks, months, and years.


Converting to Seconds

const seconds = Math.floor(diff / 1000);
  • diff / 1000 converts milliseconds to seconds.
  • Math.floor() rounds down to the nearest whole number, ensuring we get an integer value.
  • This conversion gives us the total number of seconds that have elapsed.


Converting to Minutes

const minutes = Math.floor(seconds / 60);
  • seconds / 60 converts seconds to minutes.
  • Again, Math.floor() is used to round down.
  • This conversion gives us the total number of minutes that have elapsed.


Converting to Hours

const hours = Math.floor(minutes / 60);
  • minutes / 60 converts minutes to hours.
  • Math.floor() rounds down to the nearest whole number.
  • This conversion gives us the total number of hours that have elapsed.


Converting to Days

const days = Math.floor(hours / 24);
  • hours / 24 converts hours to days.
  • Math.floor() is used to round down.
  • This conversion gives us the total number of days that have elapsed.


Converting to Weeks

const weeks = Math.floor(days / 7);
  • days / 7 converts days to weeks.
  • Math.floor() rounds down to the nearest whole number.
  • This conversion gives us the total number of weeks that have elapsed.


Converting to Months

const months = Math.floor(days / 30);
  • days / 30 converts days to months, approximating 30 days per month.
  • Math.floor() rounds down to the nearest whole number.
  • This conversion gives us the total number of months that have elapsed.


Converting to Years

const years = Math.floor(days / 365);
  • days / 365 converts days to years, approximating 365 days per year.
  • Math.floor() rounds down to the nearest whole number.
  • This conversion gives us the total number of years that have elapsed.


Returning the Relative Time String

Now, we use a series of if statements to determine which unit to use for the relative time string.

if (seconds < 60) {
    return `${seconds}s`;
} else if (minutes < 60) {
    return `${minutes}min`;
} else if (hours < 24) {
    return `${hours}h`;
} else if (days < 7) {
    return `${days}d`;
} else if (weeks < 4) {
    return `${weeks}w`;
} else if (months < 12) {
    return `${months}m`;
} else {
    return `${years}y`;
}
  • These if statements determine which unit to use for the relative time string.
  • If the difference is less than 60 seconds, we return the difference in seconds.
  • If the difference is less than 60 minutes, we return the difference in minutes.
  • If the difference is less than 24 hours, we return the difference in hours.
  • If the difference is less than 7 days, we return the difference in days.
  • If the difference is less than 4 weeks, we return the difference in weeks.
  • If the difference is less than 12 months, we return the difference in months.
  • Otherwise, we return the difference in years.
  • This approach ensures that the returned value is in the most appropriate unit, making it easy for users to understand the elapsed time.


Usage Example

To use this function, just call it with a date string like this:

const timestamp = '2025-05-29T08:17:19.945+00:00';
console.log(formatDate(timestamp));

This will output a relative time string like 5min2y, etc., depending on the difference between the current date and the input date.


Explanation of the Example

  • timestamp is a date string representing a past date and time.
  • formatDate(timestamp) calls our function, passing the timestamp as an argument.
  • The function calculates the difference between the current date and the timestamp.
  • It then converts this difference into various units and returns a relative time string.
  • The result will be a string like 5min2y, etc., depending on how much time has passed since the timestamp.


That's it! By following this guide, you can create a simple yet effective function to display relative customized time in JavaScript. This function is great for applications that need to show time differences in a friendly format. Feel free to tweak the time units and thresholds to fit your needs. Happy coding!

Recommended

Next pages: