Wrong Date format determined by Angular

8k Views Asked by At

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?

3

There are 3 best solutions below

0
On

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;
}
0
On

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

3
On

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