-2

How I can convert string (dd/MM/yyyy) format to dd/MM/yy in Angular template.

Code:

{{ stringDate | date: 'dd/MM/yy' }}

I am getting this error in console

Unable to convert "30/08/2019" into a date' for pipe 'DatePipe'

P.S - I don't want to create custom pipe.

Pratik
  • 5
  • 2
  • its new Date() | date doesn't work with string – joyBlanks Sep 26 '19 at 00:52
  • Possible duplicate of this. https://stackoverflow.com/questions/43202250/how-to-convert-string-to-date-in-angular2-typescript/43202323 – Bijay Yadav Sep 26 '19 at 03:47
  • This is a vague requirement. Why don't you want to create a custom pipe? Parsing the date string in template will make your code inefficient. – 31piy Sep 26 '19 at 03:51

3 Answers3

1

Not pretty, but this will make the pipe happy:

  {{ 
    (stringDate.split('/')[1] 
    + '/' 
    + stringDate.split('/')[0] 
    + '/' 
    + stringDate.split('/')[2])
    | date:'dd/MM/yy' 
  }}

Check the stackblitz

Lucas
  • 9,871
  • 5
  • 42
  • 52
0

Try changing 30/08/2019 (dd/MM/yyyy) to 08/30/2019 (MM/dd/yyyy) before passing it to the pipe.

The Pipe is expecting the first part of the date (30) to be the month and as 30 is greater than 12 then it does not know what to do.

Wilson
  • 608
  • 5
  • 16
0

parse the date to acceptable dateformats then use the date pipe to convert to required format you can refer the acceptable formats from here https://www.w3schools.com/js/js_date_formats.asp and to get the format as you required parse like this

new Date(parseInt(("30/08/2019").split("/")[2],10),parseInt(("30/08/2019").split("/")[1],10)-1,parseInt(("30/08/2019").split("/")[0],10))
Harish Nayak
  • 348
  • 3
  • 18