【问题标题】:Angular Date Formatting add the 'at' before time角度日期格式在时间之前添加“at”
【发布时间】:2020-12-07 22:41:40
【问题描述】:

有没有简单的方法在我的日期和时间之间添加“at”一词,所以它的内容如下:2015 年 1 月 20 日上午 11:49,而不是 2015 年 1 月 20 日上午 11:49。我尝试了longfull,但我不想显示秒数和区域设置。

    2015-01-20 16:49:07+00:00

{{ myDate | date : 'medium' }}

【问题讨论】:

    标签: angular date angular-date-format


    【解决方案1】:

    您可以通过添加新的Custom Pipe 或在您的组件中处理您的DatePipe (Angular built-in)

    已附上 Stackblitz Demo 供您参考

    方法 #1 - 自定义管道

    @Pipe({
      name: 'dateAtInsert'
    })
    export class DateAtInsertPipe implements PipeTransform {
    
      transform(value: string) {
        return value
          .replace(/,\s(?=\d+:)/g, ' ')
          .split(/\s(?=\d+:)/g)
          .join(' at ');
      }
    
    }
    
    {{ today | date : dateFormat | datAtInsert }}       // Dec 8, 2020 at 8:26 AM
    

    方法 #2 - 组件中的日期管道

    const today = new Date();
    const transformDate = this.datePipe.transform(today, this.dateFormat);
    
    this.formattedDate = transformDate
       .replace(/,\s(?=\d+:)/g, ' ')
       .split(/\s(?=\d+:)/g)
       .join(' at ');
    
    <h1>{{ formattedDate }}<h1>             // Dec 8, 2020 at 8:26 AM
    

    方法#3 - 在日期格式中添加at(组件中的DatePipe)

    dateFormat: string = 'MMM d, y AT h:mm a';        // Need to use an uppercase AT since lowercase "a" is reserved with AM/PM in date formats
                                                      // While capital "A" and "T" doesn't hold any value in date formats so it's safe to use
    
    
    const transformDate = this.datePipe.transform(this.today, this.dateFormat);
    
    this.formattedDate = transformDate.replace('AT', 'at');
    

    方法 #4 - 在日期格式中添加 at(HTML 中的 DatePipe)

    模板

    {{ insertDateAt(today | date: 'MMM d, y AT h:mm a') }}
    

    组件

    insertDateAt(date: string): string {
      return date.replace('AT', 'at');
    }
    

    注意:

    • 如果您希望您的时间采用这种格式11:49 AM,请避免使用medium,因为它包含秒数,例如11:49:29 AM
    • 改用自定义格式,在我们的例子中我们使用MMM d, y, h:mm a 或者您可以在Angular's DatePipe Documentation 找到更多格式

    【讨论】:

    • 谢谢,我决定将它们分开,以避免制作自定义管道。我不确定这是否是不好的做法:&lt;span&gt;{{myDate | date: 'MMMM d, y' }} at {{myDate | date: 'h:mm a'}
    • 嗨,没问题。我认为您的解决方案也很好,这一点毫无疑问。另外,我已经用方法#3和#4更新了答案,以防万一。希望能帮助到你。非常感谢:)
    • 感谢您的欢迎
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多