DEV Community

Ala GARBAA
Ala GARBAA

Posted on

Format Time Ago Function - Time Differences in TypeScript

Function Explanation

The following TypeScript function, formatTimeAgo, is designed to format a given date or string into a human-readable "time ago" format.
The function calculates the time difference between the provided date and the current date, presenting the result in terms of years, months, days, hours, minutes, or seconds.



export function formatTimeAgo(date: Date | string): string {

    // Initialize a default date as the current date
    let _date: Date = new Date();

    // Check if the input is a string and convert it to a Date object
    if (typeof date === "string") {
        _date = new Date(date)
    } else {
        _date = date
    }

    // Calculate the time difference in seconds
    const seconds: number = Math.floor((new Date().getTime() - _date.getTime()) / 1000);

    // Define intervals for different time units in seconds
    const intervals: Record<string, number> = {
        year: 31536000,
        month: 2628000,
        day: 86400,
        hour: 3600,
        minute: 60,
    };

    // Iterate through the intervals and determine the appropriate unit
    for (const [unit, secondsInUnit] of Object.entries(intervals)) {
        const interval: number = Math.floor(seconds / secondsInUnit);
        if (interval > 1) {
            return `${interval} ${unit}s ago`;
        } else if (interval === 1) {
            return `${interval} ${unit} ago`;
        }
    }

    // If no larger unit is found, return "just now"
    return "just now";
}

Enter fullscreen mode Exit fullscreen mode

Do your career a favor. Join DEV. (The website you're on right now)

It takes one minute and is worth it for your career.

Get started

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay