Reputation: 1308
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
Reputation: 1366
Try this
year = new Date().getFullYear()
console.log(this.year) // output 2020
Upvotes: 8
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 © {{currentYearLong()}}</p>
</footer>
Upvotes: 4
Reputation: 681
Since Year is number.
currentYear: number=new Date().getFullYear();
Upvotes: 11
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
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
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