How to customize date.now format?

2020-05-08 06:57发布

.ts

currentDate = Date.now();

.html

{{ currentDate | date }}

How can I display the time instead of Oct 25, 2019 I want it this way:

Signed this {{25th}} day of {{October}} {{2019}}?

Anyone there already implemented custom time format?

2条回答
萌系小妹纸
2楼-- · 2020-05-08 07:59

Full stackblitz with suffix and language support for month = working demo here

You can use this pipe:

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}`
      }
   }
查看更多
够拽才男人
3楼-- · 2020-05-08 08:03

You can implement a custom pipe for your date suffix and take the rest from the angular date pipe.

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>

Don't forget to add your custom pipe to module declarations!

查看更多
登录 后发表回答