有没有办法用小时替换今天的日期?

Is there a way to replace today date with hours?

我正在构建这个从数据库获取文章的应用程序,其中 1 个字段是日期,现在格式为“2019-06-13T18:03:58.000Z” 基本上我需要做的是检查这是否是今天的日期 return onyl 小时和 am/pm 所以这个例子是今天所以 return 18:03pm,如果日期是与昨天的 then return 'yesterday' 相同,如果日期不是那些,则 return 'Month, day'

我试过创建 Date 对象然后进行比较,但没有成功

我有 html 的代码:

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

并在 component.ts 文件中:

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

我需要 return 该函数中的转换日期,以便我的 html 代码打印正确的格式化日期我该怎么做?

我们无法使用 date.getTime() 准确比较两个日期,因为这将始终 return 错误,除非这两个日期精确到毫秒。 date.getTime() returns MS 日期值。

我们可以创建自己的辅助方法来确定两个日期是否是同一天,然后在您的 renderDate() 中,我们可以将 return 的逻辑调整为:

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()
}

是的,有图书馆和其他方法可以做到这一点,但这是一种方法 'by hand'。

您可以使用 toDateString 来查看今天的日期,并使用函数 formatAMPM 来显示 hh:mm AM 今天的日期

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

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

我建议您使用 custom pipe 来输出日期值。 Angular 无法缓存函数结果,因此在每个更改检测周期都会调用它们。管道仅在输入值更改时被调用。我认为这样的事情可以解决问题:

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');
    }
  }
}

这是利用内置的 Date Pipe 进行最终的字符串转换。您只需在模块的声明中添加管道,然后就可以像 {{ data.createdAt | customDatePipe}}.

一样使用它

您可以在组件中使用 angular DatePipe 和 return 转换后的日期格式,具体取决于日期比较的结果。

组件:

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();
}

模板:

{{formatDay(date)}}

您只需要在您的组件中 import { DatePipe } from '@angular/common'; 并在您的模块中添加 DatePipe : (app.module.ts 如果您没有自己的此组件模块)

 providers: [DatePipe]

这是其中的 Stackblitz