0

I have 2 variables of type Date and I need to substract them. Is there a method in angular for this or do I need to create my own?

I have tried this:

  test: Date = new Date();
  var1: Date = new Date('20-08-2018');
  var2: Date = new Date('15-08-2018');

  testsubstract() {
    this.test = this.var1 - this.var2;
    return this.test;
  }

but I get an error saying "Type number is not assignable to type Date"

user2004
  • 1,783
  • 4
  • 15
  • 42

2 Answers2

0

This is due to the fact that the subtraction results in a number and hence it reports the error as Type number is not assignable to type Date.

Hence either use the below code where you assign test as number type:-

  test: number;
  var1: Date = new Date('20-08-2018');
  var2: Date = new Date('15-08-2018');

  testsubstract() {
    this.test = this.var1 - this.var2;
    return this.test;
  }

or convert the subtraction to a date like below:-

  test: Date = new Date();
  var1: Date = new Date('20-08-2018');
  var2: Date = new Date('15-08-2018');

  testsubstract() {
    this.test = new Date(this.var1 - this.var2);
    return this.test;
  }
Ankit Sharma
  • 1,674
  • 8
  • 11
0
this.test = this.var1 - this.var2;

When you subtract two dates, the result will be in milliseconds, which is why you are getting the error. If you are looking to get the elapsed time, maybe the following link will help.

Javascript show milliseconds as days:hours:mins without seconds

Niragh
  • 162
  • 2
  • 10