Search code examples
javascriptangulartypescriptangular-pipe

How can I implement this HTML side date pipe as TypeScript code in order to convert a TimeStamp into a formatted Date?


into an Angular application I am converting a variable containing a date value in timestamp format, something like this:

patientBirthDate:  
t {seconds: 450568800, nanoseconds: 0}
nanoseconds: 0
seconds: 450568800
__proto__:

into a date from the HTML of a component, in this way:

<span class="image-text">{{patient.birthDate.toMillis() | date:'dd/MM/yyyy'}}</span>

and it works fine. Now I have to implement the same exact behavior (starting from the same field) from TypeScript code. I was trying to do:

console.log("patientBirthDate: ", patient.birthDate.toMillis());

but then what can I do to convert it into a formatted date?


Solution

  • You can inject DatePipe into your component's constructor and use this.datePipe.transform(date, '<format>');

    
    class Component {
      constructor(private datePipe: DatePipe) {}
    
      formatPatientBirthDate(patient: Patient): string {
        return this.datePipe.transform(patient.birthDate.toMillis(), 'dd/MM/yyyy');
      }
    }