The Dead Man
The Dead Man

Reputation: 5566

How to format dates in Angular 6?

I have a function which displays real time dates from entered input by user, right now when user enter the input I have something like this in front end displayed [date]:

28.10.2018 10:09

I would like the date to change if its past days , past week, past year etc

so if input was entered yesterday I would like to display something like this:

1d meaning one day ago , the same goes for year (1y) , for week (1w) etc.

Here is what I have tried so far:

Here is the function for grabing the date and its 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);
        });

And he here is the function add 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();
        const d = date.getUTCDate();
        const day = (d < 10) ? '0' + d : d;
        const m = date.getUTCMonth() + 1;
        const month = (m < 10) ? '0' + m : m;
        const year = date.getUTCFullYear();
        const h = date.getUTCHours();
        const hour = (h < 10) ? '0' + h : h;
        const mi = date.getUTCMinutes();
        const minute = (mi < 10) ? '0' + mi : mi;
        const sc = date.getUTCSeconds();
        const second = (sc < 10) ? '0' + sc : sc;
        const loctime = `${year}-${month}-${day}T${hour}`;

        this. addForm.get('localTime').setValue(loctime);

}

Here is the html for displaying to the fron end HTML:

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

Here is service function for grabing 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 do I need to change in my code to get the format I want?

Upvotes: 2

Views: 935

Answers (4)

Jayampathy Wijesena
Jayampathy Wijesena

Reputation: 1740

You could use formatDate in @angular/common. refer this link

Upvotes: 0

JBoothUA
JBoothUA

Reputation: 3149

I agree that Moment is the way to go for dealing with dates in JavaScript.

I have a couple simple angular examples here:

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

If you need me to add anything specific to that example I would be happy to do so.

EDIT

I updated the StackBlitz with a feature to output "Days, Years, etc". It's very easy, you can just take advantage of the .humanize() function

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

Nothing is hardcoded here.. I've added more examples so hopefully it starts to make sense.

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

// if you need to force to number of days
this.daysFrom2017 = this.currentDate.diff(moment('1/1/2017'), 'days');

// if you need to force to number of weeks
this.weeks = moment().diff(this.startDate, 'week');

You can force it or just use the humanize() method, which I believe is what you want, you can even set the thresholds if you need to override the defaults for it to update the humanized words.

https://momentjscom.readthedocs.io/en/latest/moment/08-durations/03-humanize/

It does however, look like there is not yet support for automatically doing a conversion to weeks, BUT it looks like it will be there very soon, here is the update/Pull Request that will add that feature:

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

But it currently supports everything but weeks

Upvotes: 1

Henry Sachs
Henry Sachs

Reputation: 302

I think you shouldn't use moment in angular. It isn't tree shakable and will make your bundle huge. You should take a look at date-fns or date.js.

Upvotes: 1

Asim Khan
Asim Khan

Reputation: 2039

Check out Moment.js to get output like "1 week ago" or "few seconds ago" etc.

Upvotes: 0

Related Questions