1

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' }}
Flash
  • 924
  • 3
  • 22
  • 44

1 Answers1

3

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
KShewengger
  • 7,853
  • 3
  • 24
  • 36
  • 2
    Thanks I decided to just break them out separately to avoid having to make a custom pipe. I'm not sure if it's bad practice or not: `{{myDate | date: 'MMMM d, y' }} at {{myDate | date: 'h:mm a'}` – Flash Dec 08 '20 at 19:50
  • 1
    Hi, no problem. I think your solution is good as well, no doubt about that. Also, I have updated the answer with Method #3 and #4, just in case. Hope it helps. Thank you very much :) – KShewengger Dec 08 '20 at 23:38
  • 1
    Thanks and Your Welcome – Flash Dec 10 '20 at 16:14
  • Good set of solutions! Unfortunately in my case I need "at" word to be locallized according to the selected language. When using angular pipe with predefined formats `long` or `full`, it is already locallized, but there is now way to include this "at" word when you create custom format :( – Tomasz Jan 26 '23 at 08:27