2

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?

4

4 回答 4

2

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}}.

于 2019-06-14T00:53:09.363 回答
2

You could use the angular DatePipe in your component and return a transformed Date format depending the result of a Date comparison.

Component:

constructor(datePipe: DatePipe) {}

date = new Date();

//returns formatted date based on date comparison  
formatDay(date): string{
  let today = new Date()
  let yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);
    
  if(this.isSameDate(today, date))        
    return this.datePipe.transform(date,'hh:mm a');
  else if (this.isSameDate(yesterday, date))
    return 'Yesterday'
  else                                       
    return this.datePipe.transform(date,'MMMM d');
 }
//checks if two dates are identical
isSameDate(d1, d2){
   return d1.getDate() === d2.getDate() && d1.getMonth() === d2.getMonth() && d1.getFullYear() === d2.getFullYear();
}

Template:

{{formatDay(date)}}

You'll just need to import { DatePipe } from '@angular/common'; in your component and add DatePipe in your module: (app.module.ts if you don't have your own module for this component)

 providers: [DatePipe]

Here's a Stackblitz of it

于 2019-06-14T00:53:50.353 回答
1

You can use toDateString to check today date, and function formatAMPM to display hh:mm AM today date

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

    if (fecha.toDateString() == today.toDateString()) {
      fecha_r = this.formatAMPM(today);
    }

    return fecha_r;
  }

  formatAMPM(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var strTime = hours + ':' + minutes + ' ' + ampm;
    return strTime;
  }

Demo https://stackblitz.com/edit/angular-format-today-date?file=src/app/app.component.html

于 2019-06-13T23:59:27.947 回答
0

We cannot compare two dates accurately using date.getTime() because this will always return false unless these two dates are the same down to the millisecond. date.getTime() returns the value of the date in MS.

We can make our own helper method to determine if two dates are the same day, then inside your renderDate(), we can adjust the logic of what to return to be:

public renderDate(date){

    const fecha = new Date(date);

    if(sameDay(new Date(), fecha){                // if is today

        return fecha.getHours() + ":" + fecha.getMinutes();

    } else if (sameDay(new Date()-1, fecha) {     // if is yesterday

        return "yesterday";

    } else {                                      //is neither

        return fecha.getMonth() + "," + fecha.getDate();

    }
}


public boolean sameDay(d1, d2) {
    return d1.getDate() === d2.getDate() && d1.getMonth() === d2.getMonth() && d1.getFullYear() === d2.getFullYear()
}

yes, there are libraries and other ways out there to do this, but this is one way to do it 'by hand'.

于 2019-06-13T23:50:35.993 回答