Building a TimePipe in Angular

Angular's DatePipe does a great job of formatting Date strings or objects into specified formats, however, if you want to pass in a time string like "09:00" you're out of luck.

The easiest way to over come this is to extend the DatePipe with some additional logic which can handle time strings and feed these into the base method. This allows you to use the standard formatting notation of Angular without having to do much.

Here is the code:

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

@Pipe({
    name: 'time'
})
export class TimePipe extends DatePipe implements PipeTransform {
    public transform(value: any, format: string): string {
        const dateTime: Date = new Date(value);

        let dateTimeString: string;
        if (this.isValidDate(dateTime)) {
            dateTimeString = dateTime.toString();
        } else {
            dateTimeString = `1970-01-01 ${value}`;
        }

        dateTimeString = dateTimeString.replace(/-/g, '/');

        if (!this.isValidDate(new Date(dateTimeString))) {
            return value;
        }

        const formattedTime: string = super.transform(dateTimeString, format);

        return formattedTime;
    }

    private isValidDate(d: any): boolean {
        return d instanceof Date && !isNaN(d.getTime());
    }
}

Here you can see that we override the transform() method and in it, immediately try and parse the inputted value. We then check if this is a valid Date, if it is not, then we assume that a time string has been passed in and concatenate this with a date value. Once we have a valid date, then we use the DatePipe's transform method and allow Angular to do the rest.

You can find the file & some tests here: github.com/adenearnshaw/ng-timepipe