Automatically generate the X-axis code for December in Echarts

Month format only

In JavaScript, you can use the following code to generate an array containing the last 13 months:

let months = [];
for (let i = 0; i < 13; i++) {
    
    
    let date = new Date();
    date.setMonth(date.getMonth() - i);
    months.push(date.getMonth());
}
console.log(months);

This code first creates an empty array months. It then forloops from 0 to 12, creating a new Dateobject each time through the loop (defaulting to the current date and time), then subtracting the current month and loop variables i. This way, each loop will get the previous month's date. Then it adds the resulting months (0 to 11) to monthsthe array.

Finally, it console.logoutputs this array using . Note that the month is expressed in numerical form here, with 0 representing January and 11 representing December. If what you want is the month name as a string, you can modify the code slightly.

Complete year and month format

In JavaScript, you can use the following code to generate an array containing the last 13 months, in the format ["2023.1", "2023.2", "2023.3", "2023.4", "2023.5", "2023.6", "2023.7" , "2023.8", "2023.9", "2023.10", "2023.11", "2023.12"]:

let months = [];
let currentYear = new Date().getFullYear();
let currentMonth = new Date().getMonth() + 1;

for (let i = 0; i < 13; i++) {
    
    
    let month = currentMonth - i;
    let year = currentYear;

    if (month < 1) {
    
    
        month += 12;
        year -= 1;
    }

    months.push(year + '.' + month.toString().padStart(2, '0'));
}

console.log(months);

This code first gets the current year and month. It then uses a forloop to go from 0 to 12, each loop calculating the previous month and adding it to monthsthe array. If the month is less than 1, it means that the year has passed. You need to subtract 1 from the year and add 12 to the month. To ensure that the month is formatted as two digits, we use padStartthe method. Finally, it console.logoutputs this array using .


@missingsometimes

おすすめ

転載: blog.csdn.net/weixin_41290949/article/details/132686481