Tom
Tom

Reputation: 8681

Displaying the year using angular 4

I am trying to display two year values on my screen using angular 4. The first is current year and the second is current year plus 7. Could you please let me know if I am doing it the correct way

component code

  currentYear = new Date();
  currentYearPlusSix = new Date();
  currentYearPlusSix1 = this.currentYearPlusSix.setDate(this.currentYearPlusSix.getFullYear() + 7 );

html

 The current year is {{currentYear | date:'yyyy'}}
  The current year plus six is {{currentYearPlusSix1 | date:'yyyy'}}

Upvotes: 3

Views: 3793

Answers (3)

Rose18
Rose18

Reputation: 3162

You need to use setFullYear

currentYearPlusSix1 = this.currentYearPlusSix.setFullYear(this.currentYearPlusSix.getFullYear() + 7 );

You can refer this for more information.

Upvotes: 0

sabithpocker
sabithpocker

Reputation: 15566

Use setFullYear to set the Year, not setDate.

setDate is clearly a wrong usage, and will give a wrong result.

 currentYearPlusSix1 = this.currentYearPlusSix.setFullYear(this.currentYearPlusSix.getFullYear() + 7 );

setDate accepts dayValue - An integer representing the day of the month. If you pass an year to it, you will get a different result

currentYear = new Date();
currentYearPlusSix = new Date();
currentYearPlusSix1 = this.currentYearPlusSix.setDate(this.currentYearPlusSix.getFullYear() + 7);

console.log(currentYearPlusSix)

Use setFullYear instead to change the years

currentYear = new Date();
currentYearPlusSix = new Date();
currentYearPlusSix1 = this.currentYearPlusSix.setFullYear(this.currentYearPlusSix.getFullYear() + 7);

console.log(currentYearPlusSix)

Upvotes: 2

Shrey Kejriwal
Shrey Kejriwal

Reputation: 736

Please make the following change:

currentYearPlusSix1 = this.currentYearPlusSix.setFullYear(this.currentYearPlusSix.getFullYear() + 7 );

setDate will only add days.

Upvotes: 0

Related Questions