What is the best way to display the time of a post update similar to the style of

I am currently working on creating a notification deck. Instead of displaying the time when a notification was received, I aim to show the time that has passed since its arrival similar to how Twitter and Facebook do it with formats like "32m" or "1 hour ago."

I am looking to implement this feature using JavaScript or Java programming languages.

Any assistance on this matter would be greatly valued. Thank you!

Answer №2

To calculate the elapsed time between now and the post's posting time, subtract the current time from the posting time in milliseconds. Use this remaining time to create a user-friendly '... ago' string.

For various JavaScript time functions, check out this link. Here is an algorithm I stumbled upon (in PHP):

function TimeAgo($datefrom,$dateto=-1)
{
    // Set default values; treat 0 as error
    if($datefrom<=0) {
        return "A long time ago";
    }
    if($dateto==-1) {
        $dateto = time();
    }

    // Calculate time difference in seconds
    $difference = $dateto - $datefrom;

    // Choose appropriate time interval based on difference
    if($difference < 60)
    {
        $interval = "s";
    }
    elseif($difference >= 60 && $difference<60*60)
    {
        $interval = "n";
    }
    elseif($difference >= 60*60 && $difference<60*60*24)
    {
        $interval = "h";
    }
    ...
    // Include more cases for different intervals

    switch($interval)
    {
        case "m":
            // Logic for month interval
            break;
        case "y":
            // Logic for year interval
            break;
        ...
        // More interval cases

    }
    return $res;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an inverted curve or border-radius for a div element is a design technique that can add

I've been tackling a project that requires me to style the border of a div in an inverted manner. To achieve this, I'm limited to using only CSS and JS without any plugins. I've searched through various online resources and similar questions ...

Are React component properties enclosed in curly braces?

I have a new component configured like this: type customType = differentType<uniqueType1, uniqueType2, uniqueType3>; function customComponent({q}: customType) When called, it looks like this: <customComponent {...myCustomVar} />, where myCus ...

Seamless side-to-side navigation

Currently, I am working on a website that has horizontal overflow instead of the common vertical scroll. While everything seems to be functioning properly, I need to enhance the user experience by adjusting the amount scrolled to move larger sections of th ...

Adjust the size of the font for the placeholder text

I've been attempting to adjust the font size of the placeholder text. I added the font size property to the listed classes below, but for some reason, it's not taking effect. Could you please advise me on how to resolve this issue so that I can ...

Addressing the issue of empty ngRepeat loops

Utilizing ngRepeat to generate table rows: <tr ng-repeat="User in ReportModel.report" on-finish-render> <td><span>{{User.name}}</span></td> </tr> An on-finish-render directive triggers an event upon completion of t ...

What could be causing my divs to overlap?

I recently started coding and I'm facing an issue with my <header> and <section> divs overlapping each other. I was under the impression that being block elements, <section> should be displayed below <header>. Any suggestions o ...

Jquery's mouseclick event selects an excessive number of elements

Is there a way to retrieve the ID of an element when it is clicked, only if it has one? I currently have this code set up to alert me with the element's ID: $("[id]").click(function(event) { event.preventDefault(); var id_name = $(this).attr ...

Adjustable icon dimensions in Material-UI

My current setup involves utilizing material-UI icons <ArrowRightAlt/> I have been able to manipulate the size of the icon using the fontSize attribute <ArrowRightAlt fontSize="large" /> However, I am interested in having the size ...

Can you explain the functionality of the const handleChange = (prop) => (event) => {} function and its significance?

While going through the documentation for MUI, I stumbled upon a new syntax for arrow functions in JavaScript that I haven't seen before. I tried to figure out how it works but couldn't find any information on it. The syntax looks like this: con ...

I am facing difficulties accessing an element within a controller in Angular

Struggling to access an element inside an AngularJS controller, I attempted the following: var imageInput = document.getElementById("myImage"); Unfortunately, this approach was unsuccessful as the element returned null. Curiously, when placing the statem ...

How to style 1 out of every 3 div elements using absolute positioning in CSS

Imagine a setup where there is a banner at the top, with 3 divs placed side by side underneath it. The interesting part is that when you scroll down, only the center and right div should move along. #banner { background:blue; color:white; position ...

Revolutionizing Form Select Field: Introducing Rails' Dynamic Input Rendering

I'm a beginner in coding, so please bear with me if my question sounds amateurish. Currently, I am developing an e-commerce website where customers can order posters from images uploaded to the site. They should be able to choose the size of the poste ...

How come the cubic bezier timing function works flawlessly just on the first try when staggered transitioning element opacity over time with CSS and a touch of JS?

I'm currently working on a menu overlay that expands to fill the screen when a user clicks a button in the corner. I'd like the menu items to fade in one by one, similar to the effect used on this website: Most of the functionality is there, but ...

The width of a CSS border determines its height, not its width

When I try to use border-width: 100px; to set the horizontal width to 100px, it ends up setting the height to 100px instead. Any help would be greatly appreciated. .border-top-green { border-top: 1px solid #4C9962; border-width: 100px; padding-t ...

Working with MongoDB collections in JavaScript to extract and manipulate array data

I have successfully parsed this array using a for loop You can view the results in the console log below. https://i.sstatic.net/zxBna.png When handling role_code in JavaScript, the following code snippet can be used: for (doctor in data.user.userType){ ...

Can a specific CSS rule be written in Material UI using makeStyles that will only apply if the element has both classes together?

It's common knowledge that achieving this in CSS is a possibility. .makeStyles-mainNavWrapper-67.sticky{ position: fixed; top: 0px; opacity: 1; transition: opacity 1s ease; padding: 10px; } I am curious to find out if this can be achieved ...

CSS-only: Align items in flexbox column with equal width and centered position, without the need for a wrapper

https://i.stack.imgur.com/vAJv2.png This particular challenge involves creating a responsive mobile menu. In this design, the width of all children is determined by the longest child element. The CSS should ensure that the .index class spans the full wi ...

Are you familiar with the Pagination and Card Components offered by Ant Design (antd)?

Can you merge the Pagination feature from antd with Card components to create a layout resembling Pinterest, complete with pagination? The standard Pagination code from https://ant.design/components/pagination/: import { Pagination } from 'antd&apo ...

AngularJS animate issue: TypeError - method 'classNameFilter' not found

When I added ngAnimate to my AngularJS app.js file as documented, I encountered a peculiar error: Object [object Object] has no method 'classNameFilter' - angular-animate.js:297 Any idea why this is happening? This is the code snippet where I ...

How can I customize the color of the Title Component in Ant Design using Styled Components?

I am currently integrating Ant Design with styled components in my project. One of the components in my application is a NavBar that includes an H1 Component. H1.tsx import React from 'react'; import { Typography } from 'antd'; impor ...