首页 > 解决方案 > Is there a way to replace today date with hours?

问题描述

I'm building this app that get articles from a DB and 1 of the fields is the date which right now is in format '2019-06-13T18:03:58.000Z' and basically what I need to do is check if this is today's date return onyl the hours and am/pm so for this example is today so return 18:03pm, if the date is the same as yesterday's then return 'yesterday'and if the date is other than those then return 'Month, day'

I've tried creating Date objects and then compare but it didn't work

I have this code for the html:

<div class='date-container'>
        {{renderDate(data.created_at)}}
    </div>

and in the component.ts file:

public renderDate(date) {
    const fecha = new Date(date);
    const today = new Date();
    const yesterday = today.getDate()-1;
    let fecha_r = '';

    if(fecha.getTime() == today.getTime()){
      fecha_r = 'today';
    }

    return fecha_r;
  }

I need to return the converted date in that function so my html code prints the correct formated date how can I do this?

标签: javascriptangulardateangular8

解决方案


I'd recommend making use of a custom pipe for you date value output. Angular isn't able to cache function results, so they get called at every change detection cycle. Pipes only get called when the input values change. I'd think something like this would do the trick:

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({name: 'customDatePipe'})
export class CustomDatePipe implements PipeTransform {
  transform(value: Date): string {
    const datePipe = new DatePipe('en-US');
    const today = new Date();
    if (today.getDate() === value.getDate() && today.getMonth() === value.getMonth() && today.getFullYear() === value.getFullYear()) {
      return datePipe.transform(value, 'hh:mmaa');
    } else {
      return datePipe.transform(value, 'MMM, d');
    }
  }
}

This is making use of the built in Date Pipe to do the final string transform. You'll just have to add the pipe in the declarations of your module and then you can use it like {{ data.createdAt | customDatePipe}}.


推荐阅读