InvalidPipeArgument: 'Unable to convert "2018-01-01-12:12:12:123456" into a date' for pipe 'DatePipe'

sm770 picture sm770 · Mar 11, 2019 · Viewed 18.3k times · Source
 <td>{{suite.testSuiteAttributes && 
       suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd'
     }}
</td>

I want the Date format in "05-Feb-2018 11:00:00 PM CST" CST format.But getting the error:

Unable to convert "2018-01-01-12:12:12:123456" into a date' for pipe 'DatePipe

I think is due to the fact that timeStamp is not in date format..but getting only this date from backend. Please suggest.

Answer

TheParam picture TheParam · Mar 11, 2019

I think you are getting the wrong format date from the server. You need a date in the valid format to convert it

So here is a workaround solution to your problem where I have written a myDateParser() method to convert your invalid date to valid date.

your.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  modifiedTimestamp;

 constructor(){

   // Passing unformatter date
   this.modifiedTimestamp = this.myDateParser('2018-01-01-12:12:12:123456');
 }

 /**
  * Custom Date parser

  */
  myDateParser(dateStr : string) : string {
    // 2018-01-01T12:12:12.123456; - converting valid date format like this

    let date = dateStr.substring(0, 10);
    let time = dateStr.substring(11, 19);
    let millisecond = dateStr.substring(20)

    let validDate = date + 'T' + time + '.' + millisecond;
    console.log(validDate)
    return validDate
  }
}

your.component.html

  <table>
    <tr>
     <td>{{modifiedTimestamp |  date: 'yyyy-MM-dd'}}</td>
    </tr>
   </table>

Solution on stackblitz

Hope this will help!