Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date Ordinal (st, nd, rd, th) in Angular?

i need to get below date format.

30th July 2019

what i try,

<time-zone  time="{{ 2019-07-31 18:30:00 }}" format="DD MMM YYYY"></time-zone>

Result : 01 Aug 2019

like image 498
Prasanga Avatar asked Aug 05 '19 03:08

Prasanga


1 Answers

You can create a custom ordinal date pipe something like

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

@Pipe({
  name: 'ordinalDate'
})
export class OrdinalDatePipe implements PipeTransform {
  transform(value: Date): string {
    if (!value) {
      return '';
    }
   let months= ["January","February","March","April","May","June","July",
           "August","September","October","November","December"]
    return `${value.getDate()}${this.nth(value.getDate)} ${months[value.getMonth()]} ${value.getFullYear()}`;
  }

 nth(d) {
  if (d > 3 && d < 21) return 'th'; 
  switch (d % 10) {
    case 1:  return "st";
    case 2:  return "nd";
    case 3:  return "rd";
    default: return "th";
  }
}
}

Add pipe to module declarations and then use it on your date like

{{dateToFormat | ordinalDate}}

StackBlitz Example

Logic inspired by this SO

like image 190
jitender Avatar answered Oct 12 '22 02:10

jitender