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

Is Angular's forkJoin being phased out?

Upon opening my Angular project today, I came across a warning message that said: The utilization of forkJoin is marked as deprecated: resultSelector is deprecated, it is recommended to use pipe to map instead (deprecation) https://i.sstatic.net/vFpeu.pn ...

Encountered a bun runtime error stating "Possibly require an `extends React.JSX.IntrinsicAttributes` constraint for this type parameter."

I have a good understanding of ReactJS, but this topic seems to be more advanced. I am working with generics in TypeScript and have the following code: export const withPopover = <T,>(WrappedComponent: React.ComponentType<T>) => { const ...

Why am I encountering an issue while trying to access req.user.id?

Having set up passport authentication on my express, node project, I encountered an error when trying to access req.user. The error message displayed is Property 'id' does not exist on type 'User'.ts(2339). Below is the relevant code sn ...

Looking for a SSR Component to Choose Dates?

In the process of designing a landing page, I encountered a challenge with incorporating a date picker feature. My goal is to have users select a date and then be redirected to another page upon clicking a button. The technology stack includes NextJS where ...

Load Order Possibly Disrupted by Arrival of Barrel Imports

When attempting to unit test my component, I keep encountering errors related to my import statements: Error: Cannot resolve all parameters for 'MyComponent'(undefined, FormBuilder). TypeError: Cannot read property 'toString' of undef ...

Having trouble deciphering the Enum definition in the Typescript Build

One of my projects utilizes a typescript package stored in npm with all the necessary definitions: index.d.ts export declare namespace OfferCraft { enum Country { es, it, fr, uk, de } enum Brand { ...

Guide on triggering a function with the Enter key in Angular 9

A button on my Angular component currently triggers a method with a (click) event, but I also want the same method to be triggered if the user presses the enter key in the input box. This gives the user flexibility. Below is the HTML code for the input an ...

Issue encountered: In Angular 8, an error is thrown stating "TypeError: Object(...) is not a function" when trying to utilize ng-idle/ng-keepalive within the eval

I've been attempting to incorporate ng-idle/ng-keepalive into my Angular 8 project, but no matter how many versions I install, the console keeps showing me this same error: Error: Uncaught (in promise): TypeError: Object(...) is not a function TypeEr ...

The property 'item' is not found within the specified type 'IntrinsicAttributes & RefAttributes<Component<{}, any, any>>'. Error code: 2322

"react": "^16.12.0", "typescript": "^4.0.3", "next": "^9.4.4" The error being raised by typescript is related to the <Item item={item} key={item.id} urlReferer={urlReferer} /> prop used ...

Compilation error occurred when running Angular with mat-form: ngcc encountered an issue while processing [email protected]

Currently dealing with a compile error in a small mat-form example that I created. Unfortunately, I am unable to pinpoint the exact issue causing this error. If you have a moment, please take a look at the code here: https://stackblitz.com/edit/angular-iv ...

Master the art of seamlessly switching between multiple kendoGridDetailTemplates in the Kendo Angular DataGrid

I am working with a Kendo DataGrid and I'm looking to use it with multiple kendoGridDetailTemplate variations. Here is an example of the kendo detail grid structure: <ng-template kendoGridDetailTemplate let-dataItem > <div>{{dataIte ...

find the element in cypress with multiple child elements

Looking for a way to target the first HTML element that contains more than 2 children. Another option is to access the children elements of the first parent element. <div class="market-template-2-columns"> <button type="button&q ...

The type '{ domain: string; parent: string; }' cannot be assigned to type 'string'. Error code: ts(2322)

Hello there! I am new to TS, so thank you for taking the time to read this. The problematic line in my code is: <this.RenderPostLink domain={r.domain} parent={r.parent} /> where I encounter an error. RenderImages = (): React.ReactElement => ...

Exciting Update: Next.js V13 revalidate not triggering post router.push

Currently using Next.js version 13 for app routing, I've encountered an issue with the revalidate feature not triggering after a router.push call. Within my project, users have the ability to create blog posts on the /blog/create page. Once a post is ...

Angular 2: Applying a class to a specific element by referencing its id

I am trying to figure out how to add a class to an element with a specific id in Angular 2. In regular JavaScript, you can do it like this, but I need help translating this into Angular 2: document.getElementById("MyElement").className += " active"; Cur ...

Is there a way to modify the id parameter in the URL using Angular 2's ActivatedRoute?

How can I modify a parameter in the URL without altering the overall address? https://i.stack.imgur.com/LOd4T.png This is the TypeScript code that I currently have: onRowClicked(event: any) { let currentIdPerson = event.data.IdPerson; } I am trying ...

Alter the navigation but keep the URL intact without modifying the view

I have an Angular project that includes a login component. The login component is located in the directory app/main/login. I am trying to navigate to the login component from app.component.html using a button. Below is the code snippet from my app-routi ...

During the present module, retrieve the runtime list of all modules that are directly imported (Javascript/Typescript)

Imagine you have a set of modules imported in the current module: import {A1, A2, A3} from "./ModuleA"; import {B1, B2, B3} from "./ModuleB"; import {C1, C2, C3} from "./ModuleC"; function retrieveListOfImportedModules() { // ...

Utilize CSS Styles with Angular 2 Component Selectors

I'm currently diving into Angular 2 and I've been pondering the idea of implementing CSS styles using the component selector in this manner: the component @Component({ selector: 'app', styleUrl: './local.css', te ...

What is the process for assigning a custom React component as the Type for a prop in another component?

Currently, I am working on a customized GenericModal component and would like to include an array of my ModalText components as props in the GenericModal for display purposes. I want to specifically define the type of prop being passed, rather than using s ...