Highcharts load pointStart from JSON. Milliseconds to UTC time? - javascript

I made a graph with Highcharts which series is loaded from JSON.
I am bit new to handle JSON file though...
I want Highcharts to show date (in formart: YYYY/MM/DD ie.2013/04/01) on label of xAxis.
As far as I know, since I cannot write something like this in JSON,
"pointStart": [Date.UTC(2013, 4, 1)]
I wrote milliseconds instead.
My JSON:
[
{
"yAxis": 0,
"type": "column",
"name": "Y label",
"data": [0,0,153,179,122,126,120,101,110,95,142,88,82,92,115,101,141,162,0,0,0,0,0,7,6,0,10,0,9,4,56,86,66,61,87,72,74,60,83,74,50,73,61,56,90,78],
"pointStart": 1364774400000,
"pointInterval": 86400000
},{
"yAxis": 1,
"type": "line",
"name": "Y label 2",
"color": "#AA4643",
"data": [4980,4572,5554,6147,5268,5221,5263,5084,4906,5000,5198,4777,4790,4549,4158,4294,4891,4689,4432,3925,3708,3723,3623,3831,3787,4353,4809,5046,4989,4815,4315,4556,4502,4725,4537,4540,4654,4367,4589,4874,4837,5032,5046,4633,4561,4576],
"pointStart": 1364774400000,
"pointInterval": 86400000
}
]
And my javascript:
var options = {
chart: {
renderTo: 'container'
},
title: {
text: ''
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%Y/%m/%d'
},
labels: {
rotation: -45,
align: 'right',
formatter: function() {
return Highcharts.dateFormat('%Y/%m/%d', this.x); //this returns invalid date.
}
},
title: {
text: ''
}
},
...
$.getJSON('test.json', function(data) {
options.series = data;
chart = new Highcharts.Chart(options);
});
This results invalid date on xAxis label.
But if I remove this part
formatter: function() {
return Highcharts.dateFormat('%Y/%m/%d', this.x);
}
returns no error but results like 1. Apr which I do not desire to show :(
Any solution to this?
Thank you.

I came up with solution as follows:
dateTimeLabelFormats: {
day: '%Y/%m/%d'
},
labels: {
rotation: -45,
align: 'right',
formatter: function() {
var _date = new Date(this.value),
_y = _date.getFullYear();
_m = _date.getMonth() + 1,
_d = _date.getDate(),
_result = _y + '/' + (_m < 10 ? "0"+_m : _m) + '/' + (_d < 10 ? "0"+_d : _d);
return _result;
}
},
...
put milliseconds value to Date object in which I was able to handle value w/ such methods as getFullYear(), getDate().
Thanks.

You have the date/time format wrong. It's not day: '%Y/%m/%d', it needs to be day: '%Y/%y/%e' see dateTimeLabelFormats Highcharts API reference.

You can use http://api.highcharts.com/highcharts#xAxis.labels.formatter and Highcharts.dateFormat() http://api.highcharts.com/highcharts#Highcharts.dateFormat()
labels: {
formatter: function() {
return Highcharts.dateFormat('%Y/%m/%d',this.value);
}

Related

How to make chartjs chart with time y-axis?

I have data something like this:
{
"measurements": [
{
"id": 10,
"key": "Demoo",
"value": "00:00:03.733;",
"date": "2023-02-08",
"time": "11:05",
"value_time_formatted": "00:00:03.733"
},
{
"id": 11,
"key": "Demooo 2",
"value": "00:00:05.191;",
"date": "2023-02-08",
"time": "11:31",
"value_time_formatted": "00:00:05.191"
},
{
"id": 12,
"key": "Demo 22",
"value": "00:00:03.002;",
"date": "2023-02-08",
"time": "11:31",
"value_time_formatted": "00:00:03.002"
}
]}
And when I try out to make a line chart from the date as labels and value_time_formatted as values I get this error:
ERROR TypeError: Cannot create property 'data' on string '00:00:03.733'
The code for bind chart values looks like this:
this.lineBarLabels = [];
this.lineBarValue = [];
res.measurements.forEach(element => {
this.lineBarLabels.push(element.date);
this.lineBarValue.push(element.value_time_formatted);
});
this.lineBar = new Chart(this.linePresents.nativeElement, {
type: 'line',
data: {
labels: this.lineBarLabels,
datasets: this.lineBarValue
}
});
this.lineBar.update();
I tried to convert that time into milliseconds but looks so ugly on-screen and the user needs to convert it back to hours, minutes, seconds, and milliseconds which is so bad from customer side :(
Your code has a few issues, here the two I could spot:
the Main error ocurres because chartjs expects a object array for the property dataset, so in your case you would have to change your code to something like this:
this.lineBar = new Chart(this.linePresents.nativeElement, {
type: 'line',
data: {
labels: this.lineBarLabels,
datasets: [{data: this.lineBarValue}]
}
});
The array this.lineBarLabels is never set (will be a empty array), you would have to change: this.lineBarLabels.includes(element.date); to this.lineBarLabels.push(element.date);
These are the main issues, I don't understand what output should you are looking for, and I don't think that setting the values to strings value_time_formatted will work, but if you fix the above mentioned points, you will be a step closer to a working chart.
Update:
It seems you fixed on mistake in your question, if you want to improve your code here is a tip for you time convertion (link to relevant documentation):
const date = new Date();
// A cleaner solution
let aShortWay = date.toISOString().substring(11,23);
// Your Sode: Not really readable, and pretty long
let yourCode = (date.getUTCHours() ? (date.getUTCHours() > 9 ? date.getUTCHours() : '0' + date.getUTCHours()) : '00') + ':' +
(date.getUTCMinutes() ? (date.getUTCMinutes() > 9 ? date.getUTCMinutes() : '0' + date.getUTCMinutes()) : '00') + ':' +
(date.getUTCSeconds() ? (date.getUTCSeconds() > 9 ? date.getUTCSeconds() : '0' + date.getUTCSeconds()) : '00') + '.' +
(date.getUTCMilliseconds() > 99 ? date.getUTCMilliseconds() : date.getUTCMilliseconds() > 9 ? '0' + date.getUTCMilliseconds() : '00' + date.getUTCMilliseconds());
console.info(`aShortWay Time:${aShortWay}`)
console.info(`yourCode Time:${yourCode}`)
I finally find a solution, hope that someone will use it in the right way :)
After this part of the code:
res.measurements.forEach(element => { this.lineBarLabels.push(element.date); this.lineBarValue.push(element.value_time_formatted); }); this.createLineChart();
I made this createLineChart() method to parse and render the chart:
public createLineChart() {
this.lineBar = new Chart(this.linePresents.nativeElement, {
type: 'line',
data: {
labels: this.lineBarLabels,
datasets: [{label: this.translate.instant('time'), data: this.lineBarValue, fill: false}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
ticks: {
callback: function (value) {
const date = new Date(Number(value) * 1000);
return date.toISOString().substring(11,23);
}
}
}
},
plugins: {
tooltip: {
callbacks: {
label: function (context) {
const date = new Date(Number(context.formattedValue) * 1000);
return date.toISOString().substring(11,23);
}
}
}
}
}
}
);
this.lineBar.update();
}

How to do customer data instead of json from the link (stockchart)

Referred this link and having doubt with this code {$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?'},
I have Json data, if i replace instead of JSON link in the stockchart,chart get disappeared. If have only from last month,the chart should display from the last month. I don't know how to replace the link with my data. And i have 2 series, can I change to line to bar in stock highcharts to column?
Please share the points for 2 series column charts with the data from server side.
I have tried,replaced the link with my server side data.
var data1=([1501545600000,150.05],[1501632000000,157.14],[1501718400000,155.57],[1501804800000,156.39],[1502064000000,158.81],[1502150400000,160.08],[1502236800000,161.06],[1502323200000,155.32],[1502409600000,157.48],[1502668800000,159.85], [1502755200000,161.60],[1502841600000,160.95],[1502928000000,157.86],[1503014400000,157.50],[1503273600000,157.21],[1503360000000,159.78],[1503446400000,159.98],[1503532800000,159.27],[1503619200000,159.86]);
var data2=([1504224000000,164.05],[1504569600000,162.08],[1504656000000,161.91],[1504742400000,161.26],[1504828800000,158.63],[1505088000000,161.50],[1505174400000,160.86],[1505260800000,159.65],[1505347200000,158.28],[1505433600000,159.88],[1505692800000,158.67],[1505779200000,158.73],[1505865600000,156.07],[1505952000000,153.39],[1506038400000,151.89],[1506297600000,150.55],[1506384000000,153.14]);
var startDate = new Date("April 01, 2016 00:00:00");
var today = new Date();
var count = parseInt((today.getTime() - startDate)/(24*3600*1000)) -1;
$.getJSON(data1, function (data1) {
// Create the chart
Highcharts.stockChart('ytdChart', {
chart: {
alignTicks: false
//type:column
},
xAxis: {
range: 9 * 30 * 24 * 3600 * 1000 // nine months
},
rangeSelector : {
enabled:false,
},
navigator: {
enabled: false
},
credits: {
enabled: false
},
title: {
text: 'YTD'
},
scrollbar: {
enabled: false
},
series: [{
// type: 'column',
name: 'YTD monthly charge',
data: data1,
tooltip: {
valueDecimals: 2
}
}
//{
//type:column,
// name: 'YTD Total',
// data: data2,
// tooltip: {
// valueDecimals: 2
// }
}
]
});
});

highcharts - 2 date picker questions

1) I am wondering how I can remove the date picker from the right side of the chart? I really only need the left rangeSelector buttons i.e. 24 hours, 6 hours...
2) is there anyway to turn off the dataLabels when you click on one of the rangeSelector options as well?
When zoomed in to show 5 minutes worth of data the dataLabels are handy, but when looking at 24 hours worth they make the chart quite unusable due to crowding. It would be nice if they could be automagically turned off when I zoomed out.
Huge thanks for your help, if this is indeed possible.
For the second option, i'm looking to toggle the visibility of
plotOptions:{series: {
dataLabels:{
enabled:true,
Fiddle Link
After customization of range selector from Highstock Example
/**
* Load new data depending on the selected min and max
*/
function afterSetExtremes(e) {
var chart = Highcharts.charts[0];
chart.showLoading('Loading data from server...');
$.getJSON('https://www.highcharts.com/samples/data/from-sql.php?start=' + Math.round(e.min) +
'&end=' + Math.round(e.max) + '&callback=?', function (data) {
chart.series[0].setData(data);
chart.hideLoading();
});
}
// See source code from the JSONP handler at https://github.com/highcharts/highcharts/blob/master/samples/data/from-sql.php
$.getJSON('https://www.highcharts.com/samples/data/from-sql.php?callback=?', function (data) {
// Add a null value for the end date
data = [].concat(data, [[Date.UTC(2011, 9, 14, 19, 59), null, null, null, null]]);
// create the chart
Highcharts.stockChart('container', {
chart: {
type: 'candlestick',
zoomType: 'x'
},
navigator: {
adaptToUpdatedData: false,
series: {
data: data
}
},
scrollbar: {
liveRedraw: false
},
title: {
text: 'AAPL history by the minute from 1998 to 2011'
},
subtitle: {
text: 'Displaying 1.7 million data points in Highcharts Stock by async server loading'
},
rangeSelector: {
buttons: [{ //customization of buttons
type: 'hour',
count: 24,
text: '24h'
}, {
type: 'hour',
count: 6,
text: '6h'
}, {
type: 'minute',
count: 5,
text: '5m'
}],
inputEnabled: false, // it remove datepicker
},
xAxis: {
events: {
afterSetExtremes: afterSetExtremes,
setExtremes: function(e) {
if(typeof(e.rangeSelectorButton)!== 'undefined')
{
if(e.rangeSelectorButton.text=='5m'){
addlables(); //function to add data label
}else{
removelables(); // function to remove data lable
}
}
}
},
minRange: 300 * 1000 // 5min * 1000
},
yAxis: {
floor: 0
},
plotOptions:{
series: {
dataLabels:{
enabled:false,
}
}
},
series: [{
data: data,
dataGrouping: {
enabled: false
}
}]
});
});
function removelables(){
var chart = $('#container').highcharts();
var opt = chart.series[0].options;
opt.dataLabels.enabled = false;
chart.series[0].update(opt);
}
function addlables(){
var chart = $('#container').highcharts();
var opt = chart.series[0].options;
opt.dataLabels.enabled = true;
chart.series[0].update(opt);
}

highcharts - show by month

highcharts by month no correct label, when is one month.
when is 2 month the label in xAxis is jan-2016 and feb-2016 but when is only one month the label is 04:59:59:999
normal: https://jsfiddle.net/rcondori/c3y1r7sn/
series: [{
data: [{
name: "January",
x: 1451624399999,
y: 52
}, {
name: "February",
x: 1454302799999,
y: 60
}]
}
]
bad: https://jsfiddle.net/rcondori/c3y1r7sn/1/
series: [{
data: [{
name: "January",
x: 1451624399999,
y: 52
}
]
help me please.
You can use the following options:
Option 1
Use Highcharts API (check example):
Highcharts.dateFormat allows you to set up the date format (for more details check this link)
labels: {
formatter: function() {
return Highcharts.dateFormat('%B-%Y', this.value);
}
}
Option 2:
Using JS method:
Check below
var temp = new Date(this.value);
locale = "en-ca",
month = temp.toLocaleString(locale, {
month: "long"
});
return month + '-' + temp.getFullYear();
By setting the variable temp as new Date (this.value), you have access to the x value (in this case the date).
month=a.toLocalString allows you to get the month on letters instead of numbers.
Here the example:
$(function() {
$('#container').highcharts({
xAxis: {
type: 'datetime',
labels: {
formatter: function() {
var temp = new Date(this.value);
locale = "en-ca",
month = temp.toLocaleString(locale, {
month: "long"
});
return month + '-' + temp.getFullYear();
}
}
},
series: [{
data: [{
name: "January",
x: 1451624399999,
y: 52
}]
}
]
});
});

Highchart UTC date always set to January, 1 1970

From an external service I am receiving a date already converted to UTC. The Highcharts tooltip is displaying Jan 01, 1970 I am not sure why it is not interpreting the date correctly. If I manually convert the UTC times to strings then user the Date.UTC JavaScript method, it works fine. I not sure why the UTC formatted date does not work.
var weightChart;
var weightData = [];
var minWeight;
var maxWeight;
$(function () {
var json = {"ibw":175,"max_weight":300,
"min_weight":175,
"weights":[{"date":1232521200,"weight":300},
{"date":1245218400,"weight":300},
{"date":1313042400,"weight":290},
{"date":1319522400,"weight":270},
{"date":1330498800,"weight":200},
{"date":1342591200,"weight":250},
{"date":1365141600,"weight":235}]};
minWeight = json.min_weight;
maxWeight = json.max_weight;
$.each(json.weights, function(i, item) {
weightData.push([item.date, item.weight]);
});
displayGraph();
});
function displayGraph() {
//graph
weightChart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
zoomType: 'xy',
height: 113
},
credits: {
enabled: false
},
title: {
text: ''
},
tooltip: {
xDateFormat: '%b %d, %Y',
headerFormat: 'Date: <b>{point.key}</b><br />',
pointFormat: 'Weight: <b>{point.y}</b>'
},
xAxis: {
type: 'datetime',
labels: {
enabled: false
}
},
yAxis: {
title: {
text: ''
},
plotLines: [{
color: '#FF0000',
width: 2,
value: 125
}],
min: minWeight,
max: maxWeight
},
series: [{
name: ['Weight'],
data: weightData
}],
exporting: {
enabled: false
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
colorByPoint: false,
pointWidth: 12,
shadow: true
}
}
});
}
Here is the fiddle for it
It looks like your data is coming from your back-end in a UNIX time stamp. Highcharts is expecting a javascript time which is UNIX time in milliseconds. It is showing Jan 01, 1970 be cause that is what "1232521200" is the date for. Multiply your datestamp by 1000 and you will get the appropriate time. Live demo.
var json = {
"ibw": 175,
"max_weight": 300,
"min_weight": 175,
"weights": [{
"date": 1232521200000,
"weight": 300
}, {
"date": 1245218400000,
"weight": 300
}, {
"date": 1313042400000,
"weight": 290
}, {
"date": 1319522400000,
"weight": 270
}, {
"date": 1330498800000,
"weight": 200
}, {
"date": 1342591200000,
"weight": 250
}, {
"date": 1365141600000,
"weight": 235
}]
};
I would recommend you to convert the date on the server side in string and supply the correct date format and then return the data as string and the highchart will display it in correct format.
For instance on the server side I have DateTime object
DateTime date=DateTime.Now
I convert the date in the correct format and return it as string date.ToString("dd.MM.yyyy")

Categories

Resources