0

I have been working with Angular 5 to show a timeline. The start and end dates are stored in DB sent from the back-end via REST.

I am getting the dates in the following format.

Start: 02-12-2019 11:26

End: 13-12-2019 13:14

As I need to convert this date to a given format, 'dd-MM-yy' I tried using datepipe and I was getting Invalid pipe argument error for the second date. -> "InvalidPipeArgument: '13-12-2019 13:14' for pipe 'DatePipe'"

Then I tried to print the dates using

Date startDate = new Date(startDateIn);
Date endDate = new Date (endDateIn);

Output:

Start Date:  Tue Feb 12 2019 11:26:00 GMT+0530 (India Standard Time)
End Date:  Invalid Date

Is there any way to make Angular know that the input date is in 'dd-mm-yyyy HH:mm' format?

Vishnu
  • 65
  • 1
  • 3
  • 10

3 Answers3

1

Javascript uses MM/DD/YYYY format as default, so when you are using:

02-12-2019 // This works but with invalid date - 12 Feb 2019

and

13-12-2019 13:14  // This doesnot because there is no 13 month

What you can do:

Use below function to change the format of the date:

changeDateFormat(date: string) {
  var dateParts = date.substring(0, 10).split("-");
  var ddMMYYYYDate = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
  return ddMMYYYYDate;
}

Working_Demo

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
0

suppose you have startDate and endDate as global variable.

  startDate: Date = new Date();

  endDate: Date = new Date();

// define constructor as

constructor(private _datePipe: DatePipe)

now in your local method.

var start= "02-12-2019 11:26";
var end="12-13-2019 11:26";      

this.startDate = <Date>(this._datePipe.transform(start, 'yyyy-MM-dd') as any);
   this.endDate = <Date>(this._datePipe.transform(end, 'yyyy-MM-dd') as any);

// do your stuff

  • https://stackblitz.com/edit/angular-8gjuet You can find the Stackblitz here. I have tried to reproduce this error. I am getting the right date for the first input string, but there is an error with second one. Also while using the html inline date pipe I am getting an output for the first date, though it is not what I want. No output for the second date there. – Vishnu Dec 02 '19 at 11:08
  • It will work, but with wrong date. The date that comes from back-end is Dec 2nd 2019 and 'mm-dd-yy' will give February 12th 2019 – Vishnu Dec 02 '19 at 11:28
  • @VishnuSoman Have you tried the posted answer? Does it solves your problem? – Prashant Pimpale Dec 03 '19 at 09:34
0

As the all mentionned above you need to format the date due to Javascript formatting your date on the wrong way, now he made a mistake.

You should us that method, but add the + in front of the dateParts element to convert them from string to number :)

changeDateFormat(date: string) {
  var dateParts = date.substring(0, 10).split("-");
  var ddMMYYYYDate = new Date(+dateParts[2], +dateParts[1] - 1,+dateParts[0]);
  return ddMMYYYYDate;
}