Search code examples
angulardateangular-date-format

Angular Date Formatting add the 'at' before time


Is there simple way to add the word 'at' in between my date and time so it reads like this: Jan 20, 2015 at 11:49 AM, instead of Jan 20, 2015, 11:49 AM. I tried long and full but I do not want the seconds and locale showing.

    2015-01-20 16:49:07+00:00

{{ myDate | date : 'medium' }}

Solution

  • You can by adding a new Custom Pipe or by dealing your DatePipe (Angular built-in) in your component

    Have attached a Stackblitz Demo for your reference

    Method #1 - Custom Pipe

    @Pipe({
      name: 'dateAtInsert'
    })
    export class DateAtInsertPipe implements PipeTransform {
    
      transform(value: string) {
        return value
          .replace(/,\s(?=\d+:)/g, ' ')
          .split(/\s(?=\d+:)/g)
          .join(' at ');
      }
    
    }
    
    {{ today | date : dateFormat | datAtInsert }}       // Dec 8, 2020 at 8:26 AM
    

    Method #2 - Date Pipe in Component

    const today = new Date();
    const transformDate = this.datePipe.transform(today, this.dateFormat);
    
    this.formattedDate = transformDate
       .replace(/,\s(?=\d+:)/g, ' ')
       .split(/\s(?=\d+:)/g)
       .join(' at ');
    
    <h1>{{ formattedDate }}<h1>             // Dec 8, 2020 at 8:26 AM
    

    Method #3 - Add at inside the date format (DatePipe in Component)

    dateFormat: string = 'MMM d, y AT h:mm a';        // Need to use an uppercase AT since lowercase "a" is reserved with AM/PM in date formats
                                                      // While capital "A" and "T" doesn't hold any value in date formats so it's safe to use
    
    
    const transformDate = this.datePipe.transform(this.today, this.dateFormat);
    
    this.formattedDate = transformDate.replace('AT', 'at');
    

    Method #4 - Add at inside the date format (DatePipe in HTML)

    Template

    {{ insertDateAt(today | date: 'MMM d, y AT h:mm a') }}
    

    Component

    insertDateAt(date: string): string {
      return date.replace('AT', 'at');
    }
    

    NOTE:

    • If you want your time to be in format like this 11:49 AM avoid using medium since it includes seconds e.g 11:49:29 AM
    • Use a custom one instead, in our case we used MMM d, y, h:mm a or you can find more formats at Angular's DatePipe Documentation