Issue
I used the below code to populate every year in the dropdown code, But I want logic to display 2024 in the dropdown when July month starts. Before that, it will show till 2023.
Likewise, 2025 will appear in the dropdown when July starts in 2025 till that it will show 2024 in the dropdown.
Please refer to my expected output.
years: number[] = [];
ngOnInit(){
for (let year = 2020; year <= d.getFullYear(); year++) {
this.years.push(year);
}
}
Expected output:
2020
2021
2022
2023
2024 Appears when July month starts in the year 2024
2025 Appears when July month starts in the year 2025
Solution
Instead of comparing by year, you should use Date.
You need to initialize date
as 1st day of July, so during iteration, it will check whether the date of 1st July is greater than the current date.
Hence, as now on January 18, 2024, the year
will not be added as the July 1, 2024 is not passed.
let years: number[] = [];
let startYear = 2020;
let now = new Date();
for (let date = new Date(startYear, 6, 1); date < now; date = new Date(date.setFullYear(date.getFullYear() + 1))) {
this.years.push(date.getFullYear());
}
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.