我正在嘗試顯示“年初至今”范圍的資料。我需要它來顯示從 2021 年 1 月的第一天到當前日期(無論今天是哪一天)的所有日期。
我以前的資料只顯示前 30 天,并且有:
const today = new Date();
const startDate =
this.startDate || new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30);
const endDate = this.endDate || today;
我怎樣才能讓資料顯示從 2021 年 1 月 1 日到今天的任何一天?
uj5u.com熱心網友回復:
以下是如何創建一個包含dateArray今年第一天和今天之間所有日期的陣列:
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() days);
return date;
}
const today = new Date()
const startDate = new Date(today.getFullYear(), 0, 1);
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= today) {
dateArray.push(new Date(currentDate));
currentDate = currentDate.addDays(1);
}
console.log(dateArray)
uj5u.com熱心網友回復:
這將適用于每一年
const aDay = 24*60*60*1000;
const end = new Date()
// normalise - otherwise I would see last day of previous year until yesterday due to timezones
end.setHours(15,0,0,0);
const start = new Date(end.getFullYear(),0,0,15,0,0,0); // 31/12/previous year to get date 0
const days = (end.getTime()-start.getTime())/aDay
let t = start.getTime();
const dates = [...Array(days)] // create an array of days
.map(() => new Date(t =aDay).toISOString().split('T')[0])
console.log(dates)
使用 while
const aDay = 24*60*60*1000;
const end = new Date()
// normalise - otherwise I would see last day of previous year until yesterday due to timezones
end.setHours(15,0,0,0);
const start = new Date(end.getFullYear(),0,0,15,0,0,0); // 31/12/previous year to get date 0
const days = (end.getTime()-start.getTime())/aDay
let t = start.getTime();
const endTime = end.getTime();
const dates = [];
while (t<endTime) {
dates.push(new Date(t =aDay).toISOString().split('T')[0])
}
console.log(dates)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360495.html
標籤:javascript 日期
下一篇:組件內的函式拋出錯誤訊息
