Highcharts date misunderstood - highcharts

I use highcharts from a long time until this January, that date is misunderstood with September.
I read a CSV file like this:
09.01.21 00:40:01;331.000;100.000
09.01.21 00:45:01;331.000;100.000
09.01.21 00:50:01;331.000;100.000
09.01.21 00:55:01;331.000;100.000
That is dd.mm.YY HH:MM:SS, 9 of January 2021, But on Highcharts I see 1 of Setember.
I tried to format date with dateFormat: 'dd/mm/YY' but don't work https://api.highcharts.com/highcharts/data.dateFormat
Here the code:
Highcharts.chart('container', {
title: { text: 'Log' },
data: { csv: document.getElementById('csv').innerHTML, itemDelimiter: ';',
lineDelimiter: '\n', decimalPoint: '.' ,dateFormat: 'dd/mm/YY'},
plotOptions: { series: { visible: false, marker: { enabled: false } } },
series: [{},{visible: true}] });
How I can solve?

Your dates are not valid with the 'dd/mm/YY' format, please check this example with valid dates: https://jsfiddle.net/BlackLabel/jgyu6q9h/
You can use the parseDate function to convert your dates to timestamps:
data: {
...,
parseDate: function(date) {
var parts = date.split(' '),
dateParts = parts[0].split('.'),
convertedDate = '20' + dateParts[2] + '-' + dateParts[1] + '-' + dateParts[0] + 'T' + parts[1];
return new Date(convertedDate).getTime();
}
}
Live demo: https://jsfiddle.net/BlackLabel/edx3cvno/
API Reference:
https://api.highcharts.com/highcharts/data.parseDate
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

Related

Highcharts CSV export, incorrect date

I have an API which returns JSON data like this:
[
{
"name":"Something",
"data":[
{
"x":1541096421,
"y":2
},{
"x":1541436378,
"y":4
},{
"x":1553621371,
"y":2
}
]
},{
"name":"Something else",
"data":[
{
"x":1541096421,
"y":2
},{
"x":1541436378,
"y":4
},{
"x":1553621371,
"y":2
}
]
}
]
The x axis represents date/time and the y axis is a score. It's plotted on a chart like this, using some formatting to convert the date from millisecond timestamp to a readable date format:
function renderChart(data) {
$('#chartContainer').highcharts({
chart: {
type: 'scatter',
zoomType: 'xy'
},
title: {
text: chartTitle()
},
xAxis: {
allowDecimals: false,
title: {
text: 'Date completed',
scalable: false
},
type: 'datetime',
labels: {
formatter: function () {
if (true) {
return Highcharts.dateFormat('%d-%b-%y', moment.unix(this.value));
}
else {
if (this.value > 0 && this.value < 24) {
return this.value;
}
else
return 0;
}
}
},
tickPixelInterval: 100
},
yAxis: {
title: {
text: 'Score'
}
},
plotOptions: {
scatter: {
marker: {
radius: 5
}
}
},
series: data,
exporting: {
buttons: {
contextButton: {
menuItems: Highcharts.getOptions().exporting.buttons.contextButton.menuItems.filter(item => item !== 'openInCloud')
}
}
// Tried adding this but it doesn't make any difference:
/*,
csv: {
dateFormat: '%d/%m/%Y'
}*/
},
tooltip: {
formatter: function () {
return 'Score of <b>' + this.y + '</b> posted on <b>' + Highcharts.dateFormat('%d-%b-%y', moment.unix(this.x)) + '</b>';
}
}
});
}
This works fine. However, when I click 'export to CSV' in the Highchart graph on the front-end it outputs a CSV file where the date is always showing as "18/01/1970". Obviously it's something to do with the fact that the API is returning a timestamp value, but I don't see how I can modify the format in the CSV similar to how it's done in the chart rendering code.
Can anyone advise how (preferably without modifying the data returned by the API) to get the CSV to output a correct date in day/month/year format?
Many thanks
It can be done easily by wrapping Highcharts.Chart.prototype.getDataRows method and map the data array which is used for export. Check demo and code posted below.
Code:
(function(H) {
H.wrap(H.Chart.prototype, 'getDataRows', function(proceed, multiLevelHeaders) {
var rows = proceed.call(this, multiLevelHeaders);
rows = rows.map(row => {
if (row.x) {
row[0] = Highcharts.dateFormat('%d-%b-%y', row.x * 1000);
}
return row;
});
return rows;
});
}(Highcharts));
Demo:
https://jsfiddle.net/BlackLabel/yafx8cb1/1/
Docs:
https://www.highcharts.com/docs/extending-highcharts/extending-highcharts
As per #Core972's comment, the issue here is related to the timestamp in the API returning the date as seconds rather than milliseconds. I don't believe there is a way to manipulate the date format in the CSV export specifically so it will require a change to the API which returns the data.
Wojciech Chmiel's answer demonstrates how to override Highchart's output to re-format the date from a non-ideal source.

Highcharts - Performance issue using chart with x values date and TIME

I am plotting a chart with ‘y’ axis being numeric values and ‘x’ axis being date time values.
I was able to process a JSON object of 3000 items. However, because of our business rules, we also need to display the time: hours + minutes in the chart’s tooltips.
This changed everything!
Now the chart takes about 15 seconds to plot 2000 records. This is unacceptable.
I can see clearly that when I remove the time part of my Date object the charts works perfectly. It is just when added the hours and minutes that performance gets affected.
Trying different things I realized that your charts should support the amount of data I am using since it is not massive.
We love the charts but performance is key for us to continue using your products.
Can you help me with this issue?
Please check this fiddle so you can understand my problem. Feel free to remove the hours and minutes variables from the DateUtc creation:
https://jsfiddle.net/17a3jry9/7/
Thanks in advance!
var pointStart = new Date();
var data = [{"date":"2017-11-08","time":"1712","perc":10},{"date":"2017-11-08","time":"1608","perc":10},{"date":"2017-11-08","time":"1506","perc":10},{"date":"2017-11-08","time":"1408","perc":10},{"date":"2017-11-08","time":"1309","perc":10},{"date":"2017-11-08","time":"1207","perc":10},{"date":"2017-11-08","time":"1110","perc":10},{"date":"2017-11-08","time":"1003","perc":10},{"date":"2017-11-08","time":"0910","perc":10},{"date":"2017-11-08","time":"0810","perc":10},{"date":"2017-11-08","time":"0708","perc":10},{"date":"2017-11-09","time":"1710","perc":10},{"date":"2017-11-09","time":"1604","perc":10},{"date":"2017-11-09","time":"1510","perc":10},{"date":"2017-11-09","time":"1406","perc":10},{"date":"2017-11-09","time":"1310","perc":10},{"date":"2017-11-09","time":"1205","perc":10},{"date":"2017-11-09","time":"1107","perc":10},{"date":"2017-11-09","time":"1010","perc":10},{"date":"2017-11-09","time":"0912","perc":10},{"date":"2017-11-09","time":"0806","perc":10}{"date":"2018-10-25","time":"0709","perc":10},{"date":"2018-10-25","time":"1009","perc":10},{"date":"2018-10-25","time":"1208","perc":10},{"date":"2018-10-25","time":"1309","perc":10},{"date":"2018-10-25","time":"1410","perc":10},{"date":"2018-10-25","time":"1510","perc":10},{"date":"2018-10-25","time":"1702","perc":10},{"date":"2018-10-26","time":"1409","perc":10},{"date":"2018-10-26","time":"0710","perc":10},{"date":"2018-10-26","time":"1505","perc":10},{"date":"2018-10-26","time":"1704","perc":10},{"date":"2018-10-29","time":"0708","perc":10},{"date":"2018-10-29","time":"1007","perc":10},{"date":"2018-10-29","time":"1208","perc":10},{"date":"2018-10-29","time":"1406","perc":10},{"date":"2018-10-29","time":"1509","perc":10},{"date":"2018-10-29","time":"1610","perc":10},{"date":"2018-10-30","time":"0710","perc":10},{"date":"2018-10-30","time":"1010","perc":10},{"date":"2018-10-30","time":"1207","perc":10},{"date":"2018-10-30","time":"1409","perc":10},{"date":"2018-10-30","time":"1510","perc":10},{"date":"2018-10-30","time":"1709","perc":10},{"date":"2018-10-31","time":"0708","perc":10},{"date":"2018-10-31","time":"1009","perc":10},{"date":"2018-10-31","time":"1206","perc":10},{"date":"2018-10-31","time":"1409","perc":10},{"date":"2018-10-31","time":"1509","perc":10},{"date":"2018-10-31","time":"1708","perc":10},{"date":"2018-11-01","time":"0707","perc":10},{"date":"2018-11-01","time":"1007","perc":10},{"date":"2018-11-01","time":"1108","perc":10},{"date":"2018-11-01","time":"1250","perc":10},{"date":"2018-11-01","time":"1509","perc":10},{"date":"2018-11-01","time":"1407","perc":10},{"date":"2018-11-01","time":"1709","perc":10},{"date":"2018-11-02","time":"0708","perc":10},{"date":"2018-11-02","time":"1007","perc":10},{"date":"2018-11-02","time":"1108","perc":10},{"date":"2018-11-02","time":"1210","perc":10},{"date":"2018-11-02","time":"1407","perc":10},{"date":"2018-11-02","time":"1509","perc":10},{"date":"2018-11-02","time":"1608","perc":10},{"date":"2018-11-02","time":"1715","perc":10},{"date":"2018-11-05","time":"0707","perc":10},{"date":"2018-11-05","time":"1007","perc":10},{"date":"2018-11-05","time":"1209","perc":10},{"date":"2018-11-05","time":"1408","perc":10},{"date":"2018-11-05","time":"1509","perc":10},{"date":"2018-11-05","time":"1611","perc":10},{"date":"2018-11-05","time":"1715","perc":10},{"date":"2018-11-06","time":"0708","perc":10},{"date":"2018-11-06","time":"1007","perc":10},{"date":"2018-11-06","time":"1201","perc":10},{"date":"2018-11-06","time":"1410","perc":10},{"date":"2018-11-06","time":"1510","perc":10},{"date":"2018-11-06","time":"1709","perc":10},{"date":"2018-11-07","time":"0708","perc":10},{"date":"2018-11-07","time":"1007","perc":10},{"date":"2018-11-07","time":"1209","perc":10},{"date":"2018-11-07","time":"1307","perc":10},{"date":"2018-11-07","time":"1410","perc":10},{"date":"2018-11-07","time":"1506","perc":10},{"date":"2018-11-07","time":"1708","perc":10},{"date":"2018-11-08","time":"0707","perc":10},{"date":"2018-11-08","time":"1009","perc":10},{"date":"2018-11-08","time":"1207","perc":10},{"date":"2018-11-08","time":"1309","perc":10},{"date":"2018-11-08","time":"1412","perc":10},{"date":"2018-11-08","time":"1508","perc":10}];
var newSeries = data.map(function (key) {
var utilDate = new Date(key.date);
var hours = parseInt(key.time.slice(0, 2));
var minutes = parseInt(key.time.slice(2, 4));
return { x: Date.UTC(utilDate.getFullYear(), utilDate.getMonth(), utilDate.getDate(), hours, minutes), y: key.perc, key: key.id };
});
Highcharts.stockChart('container', {
xAxis: {
type: 'datetime',
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Util (%)'
},
min: 0
},
tooltip: {
headerFormat: '<b>{point.x: %A, %b %e, %I:%M %p}</b><br>'
//pointFormat: '{point.x:%e. %b}: {point.y:.2f} m'
},
colors: ['teal', 'red'],
// Define the data points. All series have a dummy year
// of 1970/71 in order to be compared on the same x axis. Note
// that in JavaScript, months start at 0 for January, 1 for February etc.
series: [{
name: "Util",
data: newSeries
}],
title: {
text: 'Util Movement'
},
subtitle: {
text: ""
},
plotOptions: {
series: {
cursor: 'pointer',
turboThreshold: 10000,
point: {
events: {
}
},
label: {
connectorAllowed: false
},
pointStart: pointStart.getFullYear()
}
},
responsive: {
rules: [{
condition: {
maxWidth: 200
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
Please take a look to the browser console, you have information there about error: Highcharts error #15: www.highcharts.com/errors/15.
This means that you have unsorted data, so you need to sort them:
newSeries.sort(function(a, b){
return a.x - b.x
});
Live demo: https://jsfiddle.net/BlackLabel/onq0Lurx/

Highest value of y-axis is not shown

When using $('#container').highcharts('StockChart', { ... the highest value of the y-Axis is not shown. If I try it without StockChart, it is ok.
Example in http://jsfiddle.net/h5bSV/3/ the value 430 is missing.
Is there a possibility to show this label?
$(function() {
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=new-intraday.json&callback=?', function(data) {
// create the chart
$('#container').highcharts('StockChart', {
title: {
text: 'AAPL stock price by minute'
},
tooltip:{
formatter:function(){
return "open: " + this.points[0].point.open + 'close: ' + this.points[0].point.close + ' high: ' + this.points[0].point.high + ' low:' + this.points[0].point.low;
}
},
series : [{
name : 'AAPL',
type: 'candlestick',
data : data,
tooltip: { valueDecimals: 2}
}]
});
});
});
You need to set ShowLastLabel as true.

Custom YTD Option in HighStock Range Selector

Using the Highstock charting library, Is there any way using the Highstock Range selector to display a custom YTD option?
Current when you use a type of 'ytd' in the range selector, it defaults to using the calendar year. For my use case (and i would have thought for financial institutions as well) i need to display data running from 1st April - 31st March as a 'ytd' option
It's probably not possible without hacking sources, find in Highstock:
else if (type === 'ytd') {
now = new Date(dataMax);
year = now.getFullYear();
newMin = rangeMin = mathMax(dataMin || 0, Date.UTC(year, 0, 1));
now = now.getTime();
newMax = mathMin(dataMax || now, now);
}
So as you can see, dates are hardcoded. You can change them to needed.
Here's how i've done it. Doesn't cope with looking at a previous Financial YTD (Which is a common use case for what i need it for), but i'm sure i could hack something up to do it.
JSFiddle here
$(function() {
var startDate = new Date("April 01, 2012 00:00:00");
var today = new Date();
var count = parseInt((today.getTime() - startDate)/(24*3600*1000)) -1;
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function(data) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container'
},
rangeSelector : {
selected: 1,
buttonTheme: {
width:100
},
buttons: [{
type: 'ytd',
count: 1,
text: 'Calendar YTD'
},
{
type: 'day',
count: count,
text: 'Financial YTD'
}]
},
title : {
text : 'AAPL Stock Price'
},
series : [{
name : 'AAPL',
data : data,
tooltip: {
valueDecimals: 2
}
}]
} );
});
});

Highcharts - Rails array includes empty date entries

I'm working on a Rails 3.1.1 app with a dashboard of various line graphs using Highcharts. I implemented the sample code in Railcast 223 (highcharts) -- and everything works as expected. But on days when no entries exists, the array plots a 0 value -- but I'm only looking to line graph actual records.
Its not an issue with the Railscast because they sample has multiple Order entries each day. It appears to be the same issue posted by another user (Thomas)...though his code didn't work in my situation.
Index view:
$(function () {
new Highcharts.Chart({
chart: { renderTo: 'orders_chart' },
title: { text: 'Orders by Day' },
xAxis: { type: 'datetime' },
yAxis: {
title: { text: 'Dollars' }
},
tooltip: {
formatter: function () {
return Highcharts.dateFormat("%B %e %Y", this.x) + ': ' +
'$' + Highcharts.numberFormat(this.y, 2);
}
},
series: [{
pointInterval: <%= 1.day * 1000 %>,
pointStart: <%= 3.weeks.ago.at_midnight.to_i * 1000 %>,
data: <%= (3.weeks.ago.to_date..Date.today).map { |date| Order.total_on(date).to_f}.inspect %>
}]
});
});
class Order < ActiveRecord::Base
def self.total_on(date)
where("date(purchased_at) = ?",date).sum(:total_price)
end
end
Any input would be greatly appreciate -- new to rails and have already found the 100 ways the don't work! Thanks!
If you want nothing to be graphed but the date to still show up, then change any zeroes to a javascript null. If you want to not graph those days, then you should reject them from the array before output.
So:
(3.weeks.ago.to_date..Date.today).map{|date| total=Order.total_on(date).to_f; total.zero? ? "null" : total }.inspect
Or:
(3.weeks.ago.to_date..Date.today).map{|date| Order.total_on(date).to_f}.reject(&:zero?).inspect

Resources