I'm trying to create a datepicker with a header format that has the days abbreviated to match the day number.
The current month has 31 days, and there are 31 days printed out, but the 1st of december started last Friday, I'd like to be able to either show the days for the past week or just have the number 1 which refers to the 1st of december begin iterating under the current day, in this case it the 1 should be under F, like shown in the image below:
Here is the code that I came up with:
var currentMonthDays = [];
var monthDays = dateFns.eachDay(dateFns.startOfMonth(new Date()), dateFns.lastDayOfMonth(new Date()));
for(var day in monthDays){
currentMonthDays.push(dateFns.format(monthDays[day], 'D'));
}
var numbers = document.querySelector('.picker-days');
for(var key in currentMonthDays){
var htmlString = '<span class="picker-daysNumber">' + currentMonthDays[key] + '</span>';
numbers.insertAdjacentHTML('beforeend', htmlString);
}
I'm not sure if it's buggy, I'll have to check further, but this is what I was able to come up with to fix the problem.
First, I got the date for the first week of december, then I checked the difference in days between the first week first day and the first day of the month.
First day of the first week of the december began on the 26th, Sunday. The 1st of december was on Friday.
The difference in days was 5 days, so I just pushed empty values to the currentMonthDays array and so far it's working. Maybe I'll get the day number instead.
// organize the days in the calendar to be under the correct day abbreviation
var firstDayOfTheMonth = new Date(this.currentMonthDays.original[0]);
var monthWeekStartedOn = startOfWeek(new Date(this.currentMonthDays.original[0]));
var dayDiff = differenceInDays(firstDayOfTheMonth, monthWeekStartedOn);
for(var i = 0; i < dayDiff; i++){
this.currentMonthDays.formatted.unshift(' ')[i];
}
console.log(this.currentMonthDays);