Revathi Vijay
Revathi Vijay

Reputation: 1308

How to get the current year using typescript in angular6

How to get the current year using typescript in angular6

currentYear:Date;
this.currentYear=new Date("YYYY");
alert(this.currentYear);

It shows Invalid Date

Upvotes: 72

Views: 139120

Answers (8)

DINESH Adhikari
DINESH Adhikari

Reputation: 1366

Try this

year = new Date().getFullYear()
console.log(this.year) // output 2020

Upvotes: 8

Satyam Gupta
Satyam Gupta

Reputation: 464

This one is so easy.

In the .ts file use the following function.

  currentYearLong(): number {
  return new Date().getFullYear();
  }

and now in the html use curly bracket to access the year number.

<footer class="deep-color white-text center">
<p class="flow-text">great company &copy; {{currentYearLong()}}</p>
</footer>

Upvotes: 4

Birhan Nega
Birhan Nega

Reputation: 681

Since Year is number.

 currentYear: number=new Date().getFullYear();

Upvotes: 11

mojtaba ramezani
mojtaba ramezani

Reputation: 1559

use moment library:

import * as moment from 'moment'

moment().year(); // current year

of course you can use this code as well:

moment().format('YYYY'); // current year

Upvotes: -2

Simon Botero
Simon Botero

Reputation: 603

You can try this:

In the app.component.ts.

export class AppComponent  {
  anio: number = new Date().getFullYear();
}

In the app.component.html

{{ anio }}

I let you a Stackblitz.

https://stackblitz.com/edit/angular-byvzum

Upvotes: 38

Kenyfrank
Kenyfrank

Reputation: 63

At the import section,

import * as moment from 'moment'

At the ngOnInit,

ngOnInit(){
this.date = moment(new Date()).format('YYYY');
console.log(moment(new Date()).format('YYYY'));
}

Upvotes: 1

RAJA
RAJA

Reputation: 144

In javascript, we can get the year from date object using getFullYear().

currentYear: Date;
ngOnInit() {
  this.currentYear = new Date("2017");
  console.log(this.currentYear.getFullYear());
}

Refer this page for all date object methods

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222672

Try,

 alert((new Date()).getFullYear());

Upvotes: 128

Related Questions