I am trying to display data for a "Year to Date" range. I need it to show all the dates ranging from the first day of January 2021 until the current date (whatever day today is).
I previously had the data showing only the previous 30 days and had:
const today = new Date();
const startDate =
this.startDate || new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30);
const endDate = this.endDate || today;
How can I get the data to show from January 1st, 2021 to whatever the current day is?
CodePudding user response:
Here is how to create an array dateArray
of all dates between the first of this year and today:
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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
This will work for every current year
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)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Using 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)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>