DEV Community

Gokul Bansal
Gokul Bansal

Posted on

2

🕒 How Long Ago? A TimeAgo Component in React ⏳

📅 Timestamp: 2023-08-06T12:30:00

Ever wondered how to display the time elapsed since a specific event? 🤔 With the TimeAgo component in React, you can do just that! 🚀

Simply pass the timestamp as a prop, and the TimeAgo component will automatically calculate the time elapsed since that moment. 💡

🕑 Examples:
timestamp="2023-08-06T12:30:00" ➡️ "Less than a minute ago"
timestamp="2023-08-05T15:45:00" ➡️ "about 21 hours ago"
timestamp="2023-08-04T10:00:00" ➡️ "2 days ago"

Now you can keep your users informed about the freshness of the content or show how long ago a particular event occurred. ⏰

import { parseISO, formatDistanceToNow } from "date-fns";

const TimeAgo = ({ timestamp }) => {
    let timeAgo = "";

    if (timestamp) {
        const date = parseISO(timestamp);
        const timePeriod = formatDistanceToNow(date);
        timeAgo = `${timePeriod} ago`;
    }

    return (
        <span>
            &nbsp; <i>{timeAgo}</i>
        </span>
    );
};

export default TimeAgo;

Enter fullscreen mode Exit fullscreen mode

🚀 Give it a try and boost your app's interactivity with TimeAgo! Happy coding! 😄

Code - Github
Date-fns (npm) - Library

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (2)

Collapse
 
emmysteven profile image
Emmy Steven

Welcome to this awesome platform, what you just shared is invaluable to React Developers, please keep it up and it would nice if you write a long form content on how React developers can better use this awesome library.

Thank you.

Collapse
 
amustafa16421 profile image
Mustafa_A

thanks for sharing

good reactions so far ^^

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs