如果當前日期大于 31 日,則輸出應為(2021 年 3 月 31 日,2020 年 3 月 31 日,2019 年 3 月 31 日,2018 年 3 月 31 日,2017 年 3 月 31 日)。如果當前日期小于 31 日,則輸出應為(31 日) 2020年3月、2019年3月31日、2018年3月31日、2017年3月31日、2016年3月31日)
uj5u.com熱心網友回復:
該方法將獲取當前日期并與當前年份三月,31 個日期進行比較。如果當前日期大于 Mar,31,那么它將添加下一個 5 年的日期 31-March。如果當前日期小于 Mar,31,那么它將添加前一個 5 年的日期 31-March。
function getYearList(){
var yearList = [];
var currentDate=new Date();
//new Date(year, month, day, hours, minutes, seconds, milliseconds)
// Here 00=Jan,01=Feb,02=Mar etc.
var comparingDate=new Date(currentDate.getFullYear(),02,31);
var yearCount=currentDate.getFullYear();
if(currentDate>=comparingDate){
for (let i = 0; i <= 4; i ) {
var newDate=new Date((yearCount i),02,31);
yearList.push(newDate);
}
}else{
for (let i = 4; i >= 0; i--) {
var newDate=new Date((yearCount-i),02,31);
yearList.push(newDate);
}
}
console.log(yearList);
}
uj5u.com熱心網友回復:
PeriodChange(event: any) {
this.YearMap=[];
this.currentYear = (new Date()).getFullYear();
this.selectedYears = 5;
this.SelectedCertificate = Number(this.selectedYears);
const comparisondate = "March 31 " this.currentYear;
const requiredDate = new Date(comparisondate);
requiredDate < new Date() ? this.increment=0 : this.increment=1;
for (let i = 0; i < Number(this.CACertificateselectedYears); i ) {
this.YearMap.push("31 March " (this.currentYear-this.increment));
this.currentYear-=this.increment;
console.log(this.YearMap);
this.increment === 1 ?this.increment :this.increment ;
}
}
uj5u.com熱心網友回復:
您可以根據日期是在 3 月 31 日之前還是之后獲取開始年份,然后獲取該日期的 5 個先前實體。
通過允許用戶在默認為 5 時指定要獲取的日期數,可以使該函式更加通用。例如
// Get previous n dates for 31 March from date
function getYears(date = new Date(), n = 5) {
let year = date.getFullYear();
year -= date < new Date(year, 3, 1)? 1 : 0;
return new Array(n).fill().map(() => new Date(year--, 2, 31));
}
// Examples
console.log('Start today');
getYears().forEach(d=>console.log(d.toDateString()));
console.log('\nStart 1 Jan 2020');
getYears(new Date(2020,0)).forEach(d=>console.log(d.toDateString()));
console.log('\nGet 10 years, start today');
getYears(new Date(), 10).forEach(d=>console.log(d.toDateString()));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/331447.html
標籤:javascript 打字稿 日期
