I need to get the next 4 Thursdays with javascript, and append the result into a select box but if the current date is past Sunday, don't get the first Thursday (start a week later).
So for example:
Current date = Saturday 12th June 2021
Get Next 4 Thursdays: 17th June 2021, 24th June 2021, 1st July 2021, 8th July 2021.
Current Date = Tuesday 15th June 2021 -- Don't get 17th June 2021, so list would be:
24th June 2021, 1st July 2021, 8th July 2021, 15th July 2021.
I had some code originally that would get the thursdays for X amount of months, but this isn't quite what I want, as it gets all thursdays in one month, rather than the next 4 thursdays. I'm guessing I can reuse the get day of the week code, and modify it to just get the next 4 days... then somehow filter if the date is past Sunday?
function getNextMonths(num) {
let current = new Date();
let months = [];
for (let i = 0; i <= num; i++) {
let next = new Date();
next.setDate(1); // First day...
next.setMonth(current.getMonth() + i); //...of next month
months.push(next);
}
return months;
}
function getDayOfWeek(num_week_day, dates) {
let days = [];
var today = new Date();
for (let i = 0; i < dates.length; i++) {
// Evaluate current month
let current = {
year: dates[i].getFullYear(),
month: dates[i].getMonth()
};
current.days = new Date(current.year, current.month + 1, 0).getDate();
// Loop & evaluate days
for (let d = 1; d <= current.days; d++) {
let date = new Date(current.year, current.month, d);
if (date.getDay() == num_week_day) {
if(date.getTime() > today.getTime()){
days.push(date);
}
}
}
}
return days;
}
//Convert to Nice looking Date
function dateToString(date){
return date.toLocaleDateString("en-GB", {
dateStyle: 'full'
});
}
//Output date as mm/dd/yyyy for ouput value
function dateToValue(date){
return date.toLocaleDateString("en-GB", {
year: "numeric",
month: "short",
day: "numeric",
});
}
// Get all Thursdays (4th day of the week) within the next 2 months.
var select = document.getElementById("arr");
var elmts = getDayOfWeek(4, getNextMonths(1));
// Main function
jQuery( document ).ready(function() {
jQuery('#sub_start_date').find('option').remove();
jQuery.each(elmts, function(i, p) {
jQuery('#sub_start_date').append(jQuery('<option></option>')
.val(dateToValue(p)).html(dateToString(p)));
});
});