Showing elapsed time similar to YouTube in an Angular 8 application

Currently, I am developing an Angular application to replicate certain features found on YouTube by utilizing data fetched from an API.

This API provides video timestamps in a string format

Each timestamp follows this structure :

YYYY-MM-DDTHH:MM:SS

For instance:

2021-04-28 13:18:20.13

I intend to present this information in a text or card view in the following manner:

1 hour
1 hours ago
4 weeks ago
11 months ago
1 year ago
...

Is there a method to accomplish this using Angular without relying on any external libraries?

Answer №1

To address this issue, I took the initiative to create my own user-friendly Date Pipe. You can easily generate a Custom Date Pipe in the pipes folder by using the Angular CLI command ng g p pipes/DateAgo.

Once you execute the command, the generated file structure will include two files. If testing is not a concern for you, feel free to delete the date-ago.pipe.spec.ts file.

In the newly created date-ago.pipe.ts file, simply insert the following code:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
    name: 'dateAgo',
    pure: true
})
export class DateAgoPipe implements PipeTransform {

    transform(value: any, args?: any): any {
        if (value) {
            const seconds = Math.floor((+new Date() - +new Date(value)) / 1000);
            if (seconds < 29)
                return 'Just now';
            const intervals = {
                'year': 31536000,
                'month': 2592000,
                'week': 604800,
                'day': 86400,
                'hour': 3600,
                'minute': 60,
                'second': 1
            };
            let counter;
            for (const i in intervals) {
                counter = Math.floor(seconds / intervals[i]);
                if (counter > 0)
                    if (counter === 1) {
                        return counter + ' ' + i + ' ago';
                    } else {
                        return counter + ' ' + i + 's ago';
                    }
            }
        }
        return value;
    }

}

Don't forget to import the Custom Date Pipe in your app.modules.ts file and add it to the declarations: [...DateAgoPipe] array. If you didn't use Angular CLI to generate the Date Pipe, ensure to perform this step manually.

Lastly, update the HTML code from

<p>Published: {{dog.date | date}}</p>
to
<p>Published: {{dog.date | dateAgo}}</p>
and witness the magic unfold.

Answer №2

// Generating a date from a string:
const dateString = new Date('2021-04-28T13:18:20.13')

// Creating a current date:
const currentDate = new Date();

// Determine the time elapsed:
const timeElapsed = currentDate.getTime() - dateString.getTime();

By obtaining the time difference in milliseconds, you can then create a formula to compute years, months, days, and more.

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

Displaying svg files conditionally in a react native application

I have developed an app specifically for trading dogs. Each dog breed in my app is associated with its own unique svg file, which are all stored in the assets folder (approximately 150 svg files in total). When retrieving post data from the backend, I re ...

When invoking the function, the original state remains unaffected within a separate function

Whenever I click on an 'item', it should establish an initial value for me to use in a comparison within another function that involves the mousemove event. However, when the mousemove function is triggered, the initial state remains at 0. imp ...

Detecting the upcoming click on the document using @HostListener in Angular 4 to dynamically generate a click listener

I'm currently working on a directive that toggles its state when clicked. The desired behavior is for the state to be deactivated if the user clicks anywhere else on the page while it is active. To achieve this, I attempted to use the Renderer2 liste ...

What is the method for updating the value of the Sass variable in Angular 4?

Within the file app.component.scss, there is a variable named $color that has been set to 'red'. What steps can be taken within the file app.component.ts in order to access this variable and change its value to 'green'? ...

How to vertically align Material UI ListItemSecondaryAction in a ListItem

I encountered an issue with @material-ui/core while trying to create a ListItem with Action. I am looking for a way to ensure that the ListItemSecondaryAction stays on top like ListItemAvatar when the secondary text becomes longer. Is there any solution to ...

What is the best way to create TypeScript declarations for both commonjs modules and global variables?

Wanting to make my TypeScript project compatible with both the commonjs module system and globals without modules. I'm considering using webpack for bundling and publishing it into the global namespace, but running into issues with the definitions (.d ...

Enhancing supertest functionality with Typescript

Currently, I am working on extending the functionality of supertest. After referencing a solution from Extending SuperTest, I was able to implement the following example using javascript: const request = require('supertest'); const Test = reque ...

The Angular map function is throwing an error stating "undefined is not a function"

Currently, I'm diving into this fantastic tutorial on Angular 2 and VS Code. Following the steps, I set up a db.json server to experiment with an API using test data structured as follows: { "articles": [{ "id": 1, "name": "Wa ...

Discovering the type in Typescript by specifying a function parameter to an Interface

Consider this sample interface: interface MyInterface { x: AnotherThing; y: AnotherThingElse; } Suppose we make the following call: const obj: MyInterface = { x: {...}, y: {...}, } const fetchValue = (property: keyof MyInterface) => { ...

Is there a way for me to dissect a segment of the source map produced by source-map-explorer without any reference?

I'm currently working on an Angular 12 application and I've noticed that the bundle size is unexpectedly large, even though there are only a few components in the application. After using source-map-explorer to analyze the bundle, I discovered th ...

Issue regarding angularjs type definitions

I am facing an issue with installing typings for Angular and I need some guidance on how to resolve the error. Any suggestions or assistance would be greatly appreciated! Below is the error message that I encountered: ERROR in C:\Users\test&b ...

When using Playwright, there may arise a requirement to reuse a specific UUID that has been defined in one test within another

I have two separate tests running in parallel, each creating a different company in my test environment. However, I need to access the uuid of both companies in later tests. I am looking for a way to store these uuids so they can be used across all subseq ...

When hovering over one div, both it and another div should be displayed simultaneously. The second div should continue to be displayed even when hovered over

I am looking to keep another div displayed when hovering over it - in this example, it says "hello." The div I want to remain visible is not a child element of the main div where I initiate the hover event. document.write("<base href=\"" + docum ...

What causes the return value of keyof to vary in this particular case?

type AppleNode = { type: 'Apple' name: string score: number } type BananaNode = { type: 'Banana' id: number score: number } type FruitNodes = AppleNode | BananaNode type fruitTest = { [P in keyof FruitNodes]: 21 } // Th ...

The State of NgRX Entity is encountering undefined IDs

I decided to experiment with @ngrx/entity in a simple "Todo" project, where I had only one AppModule, one reducer, and a single component. However, as I delved into it, I encountered some challenges. The actions I defined were quite basic, focusing on CRU ...

What is causing Angular to consistently display the first object in the array on the child view, while the child .ts file correctly prints information from a different object?

Once a card of any object is clicked, the information of that specific object will be printed to the console. However, the child view will only display the details of the first object in the array it retrieves from. All pages are included below. A visual e ...

becoming a member of cdk scroll strategy notifications

In the process of creating a unique service that generates cdk overlays, I am faced with the challenge of listening to cdk scroll strategy events. Specifically, I am interested in detecting when the cdk closes an overlay using the "close" scroll strategy. ...

Setting base URLs for production and development in Angular 6: A step-by-step guide

As a beginner in Angular, I am looking for a way to set different base URLs for production and development environments. I aim to dynamically configure the base URL to avoid hard-coding it in the index.html file every time I switch between these two enviro ...

Preventing CORS issues when making HTTP requests to an Elasticsearch server using Angular hosted on Firebase

As someone who is a bit out of touch with web technologies, I'm pretty sure this question has been asked before. However, I am struggling to understand what CORS is and why it is causing my simple HTTP request to be blocked. I am currently working on ...

Troubleshooting Issue: Data not appearing on Angular frontend when fetching from Laravel API

Utilizing Laravel for the back end and Angular for the front end development. The code segments related to Angular can be found in employee.component.ts file: import { Component, OnInit } from '@angular/core'; import { DataService } from 'sr ...