如何自定义date.now格式?

时间:2019-10-25 06:34:18

标签: angular ionic3

.ts

currentDate = Date.now();

.html

{{ currentDate | date }}

我该如何显示时间而不是2019年10月25日:

  

在{{October}} {{2019}}的{{25th}}天签名了吗?

有人在实施自定义时间格式吗?

2 个答案:

答案 0 :(得分:1)

您可以为日期后缀实现自定义管道,然后从有角的date管道中取出其余部分。

import { Pipe, PipeTransform } from '@angular/core';

 @Pipe({ name: 'dateSuffix' })
 export class DateSuffixPipe implements PipeTransform {

    transform(date: Date): string {
      let day = date.getDay();
      let suffix = 'th';

      if (day == 1 || day == 21 || day == 31) {
        suffix = 'st';
      }
      if (day == 2 || day == 22) {
        suffix = 'nd';
      }
      if (day == 3 || day == 23) {
        suffix = 'rd';
      }

       return suffix;
    } 
 }

HTML

<div>
    Signed this {{currentDate | date:'dd'}}{{currentDate | dateSuffix}} day of {{currentDate | date:'LLLL yyyy'}}
</div>

别忘了将自定义管道添加到模块声明中!

答案 1 :(得分:1)

完整的stackblitz,带有后缀和语言支持,可用于月份=工作演示here

您可以使用此管道:

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "customDatePipe",
  pure: true
})
export class CustomDatePipe implements PipeTransform {
  transform(date: Date): string {
    if (!date) {
      return;
    }

    const day = date.getDate();
    const monthName = new Intl.DateTimeFormat("en-US", { month: "long" })
      .format;
    const longName = monthName(date); // "July"
    const year = date.getFullYear();

    let suffix = "th";

    if (day === 1 || day === 21 || day === 31) {
      suffix = "st";
    }
    if (day === 2 || day === 22) {
      suffix = "nd";
    }
    if (day === 3 || day === 23) {
      suffix = "rd";
    }

       return `Signed this ${day}${suffix} day of ${longName} ${year}`
      }
   }