Tips for formatting dates in Angular 6

I am currently working on a function that displays real-time dates based on user input. Currently, when the user enters the input, it is displayed in the front end as follows:

28.10.2018 10:09

However, I would like the date to change dynamically based on how long ago the input was submitted - whether it was days, weeks, or even years ago.

For example, if the input was entered yesterday, I want it to display something like this:

1d, meaning one day ago. The same logic applies for weeks (1w), years (1y), etc.

So far, I have tried implementing the following functions:

Function for retrieving the date and input text:

this.activeRouter.params.subscribe((params) => {

        let id = params['id'];
        this.userService.getComments(id)
        .pipe(
          map(data => data.sort((a, b) => new Date(b.localTime).getTime() - new Date(a.localTime).getTime()))
        )
        .subscribe(data => this.comments = data);
        });

Function for adding text input and date to the server:

addComments(task_id) {
        const formData = this.addForm.value;
        formData.task_id = task_id;
        this.userService.addComments(formData)
        .subscribe(data => {
          this.comments.push(this.addForm.value);
          this.addForm.reset();
        });
        const date = new Date();
        // more code here...
      }

HTML code for displaying the data on the front-end:

<div class="comments_details">
              <h1>Mike Ross</h1>
              <span class="days">{{comment.localTime | date:'dd.MM.yyyy H:mm'}}</span>
            </div>

Service function for fetching and adding data to the server:

addComments(comments: Comment) {
    comments.localTime = new Date();
    return this.http.post(this.commentsUrl, comments);
}
getComments(id: number) {
    return this.http.get<Comment[]>(this.commentsUrl);
}

What changes do I need to make in my code to achieve the desired date format?

Answer №1

In my opinion, avoiding the use of Moment in Angular is advisable due to its lack of tree shakability and potential impact on bundle size. Instead, consider exploring alternatives like date-fns or date.js for your date processing needs.

Answer №2

When it comes to handling dates in JavaScript, I am in agreement that Moment is the best tool for the job.

If you're looking for some straightforward Angular examples, feel free to check out this link:

https://stackblitz.com/edit/angular-moment-example

If there's anything specific you'd like me to add or customize in those examples, just let me know!

UPDATE

I've made an addition to the StackBlitz demo where it now showcases outputting "Days, Years, etc." It's a simple process using the .humanize() function

this.humanized = moment.duration(moment().diff(this.startDate)).humanize();

Nothing is hardcoded here. I've included more instances so that it becomes clearer how it all works.

this.humanized = moment.duration(moment().diff(this.startDate)).humanize();
this.humanizedNow = moment.duration(moment().diff(moment())).humanize();

// To calculate number of days
this.daysFrom2017 = this.currentDate.diff(moment('1/1/2017'), 'days');

// To calculate number of weeks
this.weeks = moment().diff(this.startDate, 'week');

You have the option to specify calculations or simply utilize the humanize() method, which I assume is what you're aiming for. You can even modify the thresholds if needed to adjust the humanized terminology.

As of now, automatic conversion to weeks doesn't seem to be supported, but based on recent updates, it appears that this feature will soon be available. Here's the relevant update/Pull Request:

https://github.com/moment/moment/pull/4570/files

Everything else is supported except for weeks at the moment.

Answer №3

If you want results such as "1 week ago" or "a few seconds ago," consider using Moment.js.

Answer №4

One option is to utilize the formatDate function found in the @angular/common library. To learn more, you can visit this useful link

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

Programmatically link an Angular JS model to a template using binding

When given an HTML template like the following: <div class="info"> <div class="title"><a href="property-detail.html">{{title}}</a></div> <div class="location">{{location}}</div> <div class="property ...

How to Implement Modal Popups on Click in Angular with the AmCharts XY Chart

Our goal is to display a modal window when users click on a data point. The current code we are using is as follows: constructor(public dataservice: DataserviceService, private modalService: NgbModal, private router: Router) { } ... ... bullet.events.on( ...

The Tumblr HTML code is not valid: There is a stray start tag for `html

Occasionally, I check my tumblog for validation in order to fix any errors. While most issues are easy to explain, there is one that has me stumped. What exactly does this mean? (please note: the outputted markup is out of my control) Error: Error: Stra ...

Discovering the breakpoints for Angular ng-bootstrapUncover the angular ng

Utilizing ng-bootstrap in my latest project has allowed me to easily create a grid with breakpoints, like so: <div class="row"> <div class="col-sm-12 col-md-6 col-xl-4"></div> </div> Although these breakpoints are convenient, ...

I'm looking to adjust the position of an image inside a div without affecting the position of the entire div

When creating a horizontal navigation bar with an image, I encountered an issue where the image link did not align with the rest of the links on the navigation bar. I wanted to drop it down by a pixel or two without affecting the position of the other link ...

Preventing input in one textbox if another textbox has a filled value in HTML

Apologies for asking this question, but is there a way to disable one text box if another text box has a value? I've attempted using the following code, but it doesn't seem to work. Sorry for the inexperienced inquiry T_T function disableTextbox ...

What is the process for importing DataTables using npm?

My attempt to import "datatables.net-select" using the usual method doesn't seem to be working. After checking the website, I found that the correct way to do it is: var $ = require( 'jquery' ); var dt = require( 'datatable ...

Encountered a PrismaClientValidationError in NextJS 13 when making a request

I am currently working on a school project using NextJS 13 and attempting to establish a connection to a MYSQL database using Prisma with PlanetScale. However, when trying to register a user, I encounter the following error: Request error PrismaClientValid ...

Is it better to dynamically generate HTML elements or to just directly paste complete fragments in the code?

After manipulating the DOM and injecting AJAX content, I often find myself filling in the new content into a copied HTML fragment, then populating it with the updated information before using $().html() to insert the modified code back into the DOM. The ex ...

Reacting to multiple checkboxes in a check handling system

In my latest project, I have designed a component that utilizes multiple checkboxes generated within a .map function. While testing the functionality, it came to my attention that users could select more than one checkbox at a time. This is not ideal as th ...

Disallow negative numbers but allow decimals in HTML input

I need help restricting user input to prevent negative numbers while still allowing floating point numbers in my Angular project. Any suggestions using Angular tools would be greatly appreciated. Thanks! ...

Difficulty altering value in dropdown using onChange function - Material-UI Select in React app

Having trouble updating dropdown values with MUI's Select component. The value doesn't change when I use the onChange handler, it always stays the same even after selecting a new item from the dropdown. I made a functional example on CodeSanbox. ...

Having difficulty centering an image in HTML?

I've been struggling to get the image (logo) centered on the top bar! I've tried using align-self: center;, display:block;, but nothing seems to work. It feels like I'm missing something here! Click here for the codesandbox link to view the ...

Strapi: Enhancing User Experience with Unique Passwordless Customization Services

I have been attempting to modify the "passwordless" strapi plugin in order to generate verification codes consisting exclusively of digits. To achieve this, I need to override the createToken function within the plugin's service. Following the instru ...

Adding HTML elements dynamically using jQuery: A how-to guide

My objective is to start with one element upon loading the page, and this element should have an ID of "something_O". When the user clicks on an add link, a new identical HTML element should be added underneath the existing element. The new element should ...

Eliminate repeated elements in a selection using an AngularJS custom directive

I am in the process of creating an events app that utilizes JSON data from Drupal to showcase events using AngularJS within a Drupal module. One of the keys in the JSON object is 'genre', which I'm utilizing in a select dropdown to allow use ...

Using TypeScript with Node.js: the module is declaring a component locally, but it is not being exported

Within my nodeJS application, I have organized a models and seeders folder. One of the files within this structure is address.model.ts where I have defined the following schema: export {}; const mongoose = require('mongoose'); const addressS ...

Executing a PHP script to initiate a ping transmission

I have a project to complete for my university involving the development of a simple application. However, I lack experience in this area and am unsure how to proceed. The objective is straightforward: I want to send ping requests to 50 IP addresses at t ...

Easily refresh multiple select options by using the ajax updater function in prototype

After carefully reviewing the documentation for Ajax.Updater(), I noticed that the first argument to the constructor should be container (String | Element) – The DOM element whose contents will be updated as a result of the Ajax request. This can eith ...

Sending a function return to a React component

What I want to achieve is sending the response from an API call to a React Component and using it to generate a List. My confusion lies in how to pass the value from a function to the component. Do I require state for this process? searchMealsHandler(even ...