How can I show the week number for the date in Highstock (not Highcharts!)?
My SQL looks like this
select unix_timestamp(date)*1000 week
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.
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);
},