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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With