【问题标题】:Is there a way to replace today date with hours?有没有办法用小时代替今天的日期?
【发布时间】:2019-10-28 14:16:09
【问题描述】:

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

我尝试过创建 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;
  }

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

【问题讨论】:

    标签: javascript angular date angular8


    【解决方案1】:

    您可以在组件中使用角度 DatePipe 并根据日期比较的结果返回转换后的日期格式。

    组件:

    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

    【讨论】:

    • 我已经尝试过您提供的代码,但出现此错误:d2.getDate is not a function at ArticleComponent.isSameDate (article.component.ts:36) at ArticleComponent.formatDay (article.component. ts:27)
    • 您确定每次调用isSameDate() 时都为每个参数传递了Date 变量吗?如果你不能让它工作,请参考我链接的 Stackblitz,这是一个完全有效的解决方案
    • 我解决了这个问题,问题是我从 mongo 收到了这种格式的日期:“2019-03-13T03:18:22.000Z”,当你的函数试图比较日期时这种格式“Thu Jun 13 2019 22:03:22 GMT-0400 (Venezuela Time)”所以解决方案是创建一个 let fecha = new Date(date) 然后与 fecha 进行所有比较
    【解决方案2】:

    我建议您使用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}} 一样使用它。

    【讨论】:

      【解决方案3】:

      您可以使用 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

      【讨论】:

        【解决方案4】:

        我们无法使用date.getTime() 准确比较两个日期,因为这将始终返回 false,除非这两个日期精确到毫秒是相同的。 date.getTime() 返回 MS 中的日期值。

        我们可以制作自己的辅助方法来判断两个日期是否是同一天,然后在你的renderDate()中,我们可以调整返回什么的逻辑:

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

        是的,有图书馆和其他方法可以做到这一点,但这是“手工”完成的一种方法。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-06-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多