I’m trying to build a simple list of links that shows the next 12 months, starting with the current month. The output would look like this:
<div class="dateLinks">
<a href="example.com/ShowCalendar.asp?chdate=02/01/2024">February 2024</a>
</div>
<div class="dateLinks">
<a href="example.com/ShowCalendar.asp?chdate=03/01/2024">March 2024</a>
</div>
....etc
The link text is the month and year and the href value is the first day of each month.
This is my code so far, but there has to be a more elegant way than just some long list of possible months, which needs to be updated at some point.
var theMonths = new Array("January 2024", "February 2024", "March 2024", "April 2024", "May 2024", "June 2024", "July 2024", "August 2024",
"September 2024", "October 2024", "November 2024", "December 2024", "January 2025", "February 2025", "March 2025", "April 2025", "May 2025", "June 2025", "July 2025", "August 2025", "September 2025", "October 2025", "November 2025", "December 2025");
var theDates = new Array("1/1/2024", "2/1/2024", "3/1/2024", "4/1/2024", "5/1/2024", "June 2024", "July 2024", "August 2024",
"September 2024", "October 2024", "November 2024", "December 2024", "January 2025", "February 2025", "March 2025", "April 2025", "May 2025", "June 2025", "July 2025", "August 2025", "September 2025", "October 2025", "November 2025", "December 2025");
var today = new Date();
var aMonth = today.getMonth();
var i;
for (i = 0; i < 12; i++) {
document.write1('<div class="dateLinks"><a href="example.com/ShowCalendar.asp' + '?chdate=' + [aDate] + '">');
document.writeln(theMonths[aMonth] + '</a></div>'); //here you can do whatever you want...
aMonth++;
if (aMonth > 11) {
aMonth = 0;
}
}
2
Answers
Here is a way to do it with
toLocaleString
: call it once to generate the "February 2024" style and another time to get the "02/01/2024" format, just by giving different options as argument.The year and month can be iterated in different ways. Here I’ve used a "yearmonth" counter, that counts a year as twelve months, and then breaks that number into the two components to create the actual date:
I wouldn’t necessarily argue with code that works. That said, it would probably make more sense to consolidate like pieces, such as the month names and years into a more compact constant, then you can use strings to pull the pieces together, similar to this: