How to mark weekends with plotBands in HighCharts

So you have a plot y vs time and you want to denote different days of a week with plotBands. The only problem is, you want to do it dynamically, only from the beginning of your data to the end. Welcome to my world a couple of days ago.

We want something like this. Have some visual background reference for weekends (or even separately for Saturday and Sunday.

This is surely built in to Highcharts. A long google session later: Nope.

There surely is someone who asked this. Yes. Correct. You stumble upon something like https://stackoverflow.com/questions/63629998/highlight-weekend-with-a-plot-band-or-a-zone. Looks perfectly like what you want. After the chart is loaded, it goes over all the data and marks the weekends. Except it doesn’t work if you import data using the HighCharts data module! And the debugging takes another day.

You turn to the old reliable Python, and want to hardcode into the file all the weekends in this century. But surely there must be a way to do it in JS. It can use the fact, that the initial date is known and constant, and that the ending date is today. After too much googling, but you are tired of solutions that don’t work, you arrive at the following 5 lines of code 1

var now = new Date();
var weekends = [];
for (var d = new Date(2021, 9, 1); d <= now; d.setDate(d.getDate() + 1)) {
    if (d.getDay() == 6 || d.getDay() == 0) {// 6 is Saturday, 0 is Sunday
        weekends.push(new Date(d))
    }
}

So much frustration for f****** 5 lines of code.

Well, to fully use this in HighCharts there are a few more lines, but that was the gist. Full code is below. A working example (with different color for Saturday and Sunday) is also on http://quick.blameitonthegoose.com/static/dizel.html, just don’t mind the bad design.

var now = new Date();
var weekends = [];
for (var d = new Date(2021, 9, 1); d <= now; d.setDate(d.getDate() + 1)) {
    if (d.getDay() == 6){
	    weekends.push({ // mark the weekend
                color: "rgba(220, 118, 51, 0.2)", // some color with possible transparency
                from: new Date(d),
                to: new Date(d.setDate(d.getDate() + 2)) // for weekend lasting from Sat 0:00 to Mon 0:00. Change if needed
                })

    }
}


// and add this to the Highcharts chart entity
    xAxis: {
        plotBands: weekends,
    },
  1. Technically 7, but realistically, it could go down to 5 whilst remaining readability.