Highstock - display number of week

风格不统一 提交于 2019-12-02 01:18:45

You can add it using dateFormats, for example: http://jsfiddle.net/EkAnm/

Highcharts.dateFormats = {
    W: function (timestamp) {
        var date = new Date(timestamp),
            day = date.getUTCDay() == 0 ? 7 : date.getUTCDay(),
            dayNumber;
        date.setDate(date.getUTCDate() + 4 - day);
        dayNumber = Math.floor((date.getTime() - new Date(date.getUTCFullYear(), 0, 1, -6)) / 86400000);
        return 1 + Math.floor(dayNumber / 7);

    }
}

Then use it in or format or dateFormat():

xAxis: {
        tickInterval: 7 * 24 * 36e5, // one week
        labels: {
            format: '{value:Week %W/%Y}'
        }
    },

For @Paweł Fus 's answer, I find out that when the date is 2012/1/1 witch was Sunday,the result is wrong, so I have changed the answer to :

W: function (timestamp) {
    var date = new Date(timestamp);
    var firstDay = new Date(date.getFullYear(), 0, 1); 
    var day = firstDay.getDay() == 0 ? 7 : firstDay.getDay();
    var days = Math.floor((date.getTime() - firstDay)/86400000) + day; // day numbers from the first Monday of the year to current date
    return Math.ceil(days/7);
},

To keep weeks and years consistent, I tend to use ISO-8601 standard when dealing with week numbering.

With Pawel answer and the js code from this blog, I set up the following solution.

Highcharts.dateFormats = {
        V: function (timestamp) {    
            var target  = new Date(timestamp);  
            var dayNr   = (target.getDay() + 6) % 7;  
            target.setDate(target.getDate() - dayNr + 3);  
            var firstThursday = target.valueOf();  
            target.setMonth(0, 1);  
            if (target.getDay() != 4) {  
                target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);  
            }  
            return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000  
        }  ,
        G: function(timestamp) {
            var target  = new Date(timestamp);  
            target.setDate(target.getDate() - ((target.getDay() + 6) % 7) + 3);  
            return target.getFullYear();  
        }
};

%V and %G respects the strftime format used in highstock.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!