DatePipe for time conversion

Viewed 161

I need to convert a time string (eg. 19:07:33 to 19:03) this data value is retrive from db via API.

<ion-col size="3" class="col">{{res.oraIT |date:'HH:mm' }}</ion-col> 

Here the error console:

core.js:6210 ERROR Error: InvalidPipeArgument: 'Unable to convert "19:07:33" into a date' for pipe 'DatePipe'
at invalidPipeArgumentError (VM33256 vendor.js:105476)
at DatePipe.transform (VM33256 vendor.js:105867)
at pureFunction2Internal (VM33256 vendor.js:81497)
at ɵɵpipeBind2 (VM33256 vendor.js:81671)
at TimbraHomePage_section_24_div_4_div_13_Template (VM33767 TimbraHomePage.js:269)
at executeTemplate (VM33256 vendor.js:65469)
at refreshView (VM33256 vendor.js:65335)
at refreshEmbeddedViews (VM33256 vendor.js:66460)
at refreshView (VM33256 vendor.js:65359)
at refreshEmbeddedViews (VM33256 vendor.js:66460)
1 Answers

DatePipe accepts Date, string, or number. But they all need to represent a valid Date. First, you could do this:

<ion-col size="3" class="col">{{toDate(res?.oraIT) | date : 'HH:mm' }}</ion-col> 

In angular component:

public toDate(fromAPI: string): Date {
  let time: string = fromAPI || '00:00:00';
  return new Date(`01-01-00 ${time}`);
}

Understandably, you might not want to run a function when DatePipe also accepts a string. Unfortunately, as far as I know Angular interpolation still does not accept string template literals so you probably could only get away with something like this:

<ion-col size="3" class="col">{{'01-01-00 ' + (res?.oraIT || '00:00:00') | date : 'HH:mm' }}</ion-col>

Or you could just make your own DatePipe that did what you want:

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

@Pipe({ name: 'date2' })
export class DatePipe implements PipeTransform {
    public transform(data: string): string {
        let time: string = data || '00:00:00';
        let date: Date = new Date(`01-01-00 ${time}`);
        let hrs: string = this.pad(`${date.GetHours()}`, 2);
        let mins: string = this.pad(`${date.GetMinutes()}`, 2);
        return `${hrs}:${mins}`;
    }

    public pad(s: string, n: number): string { 
      return s.padStart(n, '0'); 
    }
}

Add that datepipe to app.module declarations and it simplifies your html:

<ion-col size="3" class="col">{{res?.oraIT | date2}}</ion-col> 
Related