Klaus
Klaus

Reputation: 1731

Is there a way to get the formatted date output with Angular Pipes

I have a ISO Zone Date Time String which looks something like '2020-01-15T10:45:20+02:30[US/Denver]'. I am trying to get an angular pipe to make this look something like '15 Jan 2020 ( US/Denver )'. What would be the best way to do this.

Currently I do not have a proper pipe implementation on this and this is how I have achieved the expected output

{{ dateInput | date:"dd-MMM-yyyy" }}{{ someFuntionThatReturnsTimeZoneWithStringManipulation() }}

Thanks in advance

Upvotes: 1

Views: 735

Answers (1)

Barremian
Barremian

Reputation: 31125

You could extend the default date pipe, split the string, transform the date and return back the combined string.

Here is a quick implementation

Pipe

import { Inject, LOCALE_ID, Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
  name: 'dateLocation',
  pure: true
})
export class DateLocationPipe extends DatePipe implements PipeTransform {
  constructor(@Inject(LOCALE_ID) locale: string) {
    super(locale);
  }

  transform(value: any, format?: string, timezone?: string, locale?: string): any {
    const date = value.split('[');
    return super.transform(date[0], format, timezone, locale) + ' (' + date[1].replace(/\]/g, ')');
  }
}

Component template

{{ dateInput | dateLocation:"dd MMM yyyy" }}

Working example: Stackblitz

Update: Ignore UTC Time Offset

You could perform one more split over the + sign and ignore the time offset of the time stamp.

Pipe

return super.transform(
    date[0].split('+')[0], 
    format, 
    timezone, 
    locale
  ) + 
  ' (' + 
  date[1].replace(/\]/g, ')');

Working example: Stackblitz

Upvotes: 1

Related Questions