Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2/4/5 display dates with suffix (st, rd and th) in expression

Tags:

angular

What would be the best "Angular way" to add suffix (st, rd and th) to dates in Angular 2/4/5/... ?

For example: February 25th, March 1st, April 2nd in an Angular expression {{item | date: ???}}

The suffix options do not seem to be covered in the Angular Date Pipe doc.

like image 226
Pat M Avatar asked Feb 04 '23 02:02

Pat M


2 Answers

Thank you Roddy,

So meanwhile that the Angular team come up with some core feature for date suffixes, here's the simplistic pipe I came up with.

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

@Pipe({ name: 'dateSuffix' })
export class DateSuffix implements PipeTransform {
    transform(value: string): string {

    let suffix = 'th',
        day = value;

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

        return suffix;

    }
}

and once imported in the component...

I use an expression like this

{{record.RecordDate | date: "MMM.d"}} 
<span class="text-superscript">
    {{(record.RecordDate | date: "d") | dateSuffix}}
</span>

which outputs something like Apr.3rd

like image 61
Pat M Avatar answered Feb 07 '23 11:02

Pat M


This is not a feature currently supported by Angular -- well, not out-of-the-box.

As you noticed, the Angular Date Pipe documentation does not mention ordinals. Therefore, you will need to write your own pipe to support this functionality and use that in place of the built-in date pipe. I would suggest using the source of the date pipe as a starting point, and also the reference documentation about writing pipes.

For further reference, note that there is an open feature request for this functionality.

like image 39
Roddy of the Frozen Peas Avatar answered Feb 07 '23 13:02

Roddy of the Frozen Peas