How to change UTC timestamp on the Highstock charts? - javascript

I have an API at https://gmlews.com/api/data. And my code for highstock charts in http://jsfiddle.net/estri012/b5nhezLs/8/ .
My problem is my timestamp look like this "2020-03-15T11:46:10+07:00". So on the chart it should shows 15 March 11:46 instead of 15 March 04:46. But the chart show UTC time. How to fix it, so the chart show the local same time with mine? And the last three data on the chart show 18 March instead of 19 March. In my API, the last three data must be 19 March not 18 March.
$(function () {
$.getJSON('https://gmlews.com/api/data', function (data) {
console.log(data);
function format_two_digits(n) {
return n < 10 ? '0' + n : n;
}
var accelero_x = [], timestamp = [];
for (var i=0; i<data.length; i++){
let inArr = [];
inArr.push(Date.parse(data[i].timestamp));
inArr.push(data[i].accelero_x);
accelero_x.push(inArr);
timestamp.push(data[i].timestamp);
}
console.log(accelero_x);
console.log(timestamp);
// Create the chart
window.chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
inputEnabled: true,
buttons: [{
type: 'day',
count: 1,
text: '1D',
},
{
type: 'week',
count: 1,
text: '1W',
},
{
type: 'month',
count: 1,
text: '1M',
},
{
type: 'year',
count: 1,
text: '1Y',
}, {
type: 'all',
count: 1,
text: 'All',
}],
inputDateFormat: '%d-%m-%Y',
inputDateParser: function (value) {
value = value.split('-');
return Date.UTC(
parseInt(value[2]),
parseInt(value[1]) - 1,
parseInt(value[0])
);
},
},
title: {
text: 'Accelero X'
},
xAxis: {
type: "datetime",
labels: {
/* format: '{value:%Y-%m-%d}', */
formatter: (currData) => {
const currDate = new Date(currData.value);
return format_two_digits(currDate.getHours()) + ':' + format_two_digits(currDate.getMinutes());
},
rotation: 45,
align: 'left'
}
},
series: [{
name: 'Accelero X',
data: accelero_x,
type: 'spline',
tooltip: {
valueDecimals: 2
}
}]
}, function (chart) {
// apply the date pickers
setTimeout(function () {
$('input.highcharts-range-selector', $('#' + chart.options.chart.renderTo)).datepicker();
}, 0)
});
});
// Set the datepicker's date format
$.datepicker.setDefaults({
dateFormat: 'dd-mm-yy',
beforeShow: function() {
var date = $(this).val().split('-');
$('input.highcharts-range-selector').datepicker("setDate", new Date(parseFloat(date[0]), parseFloat(date[1]) - 1, parseFloat(date[2])));
},
onSelect: function (dateText) {
this.onchange();
this.onblur();
}
});
});

Try to set time.useUTC to false - https://api.highcharts.com/highcharts/time.useUTC
Demo: http://jsfiddle.net/BlackLabel/avhw7km8/
time: {
useUTC: false
},

Related

How to change the range of x axis through drowpdown menu - javascript plotly

I am trying to create a chart with plolty.js that displays a time series with different values. I have already added rangeselectors to change the time period of the displayed values. I also want to add a dropdown menu to change the range of xaxis (actually the beginDate). I tried to change xaxis.range with the relayout method. But somehow it always shows the year 2000 when I click on a
It would be great if you could help me!
buttonsDates=[];
first = beginDate.getFullYear();
end = endDate.getFullYear();
for(i = first; i <= end; i++) buttonsDates.push({
label: i, method: 'relayout',args: [
{
'xaxis.range': '[new Date(i,1),new Date(i,12)]',
'xaxis.rangeslider': '[type:date, range:[new Date(i,1),new Date(i,12)]]'
}]
});
var myPlot = node.children[0],
trace1 = {
x: values.map(a => a.xvalue), y: values.map(a => a.yvalue),
type: 'scatter',
name: 'Messwert des Patienten',
locale: 'de_DE',
hovertemplate: '<b>Wert: </b> %{y}' +
'<br><b>Datum: </b> %{x}<br>'
},
data = [
trace1
],
layout = {
title: 'Verlaufswert: ' + vitSigTitle,
hovermode: "closest",
showlegend: true,
xaxis: {
autorange: true,
range: [beginDate, endDate],
rangeselector: {
buttons: [
{
count: 1,
label: 'Tag',
step: 'day',
stepmode: 'backward'
},
{
count: 1,
label: 'Woche',
step: 'week',
stepmode: 'backward'
},
{
count: 1,
label: 'Monat',
step: 'month',
stepmode: 'backward'
},
{
count: 6,
label: '6 Monate',
step: 'month',
stepmode: 'backward'
},
{
count: 1,
label: 'Jahr',
step: 'year',
stepmode: 'backward'
},
{
count: 1,
label: 'Dieses Jahr',
step: 'year',
stepmode: 'todate'
},
{
label: 'Gesamt',
step: 'all'
}
]
},
rangeslider: { range: [beginDate, endDate] },
type: 'date'
},
yaxis: {
title: vitSigUnit,
autorange: false,
range: [minValue - 10, maxValue + 10],
type: 'linear',
locale: 'de_DE'
}, updatemenus: [{
buttons:
buttonsDates
}]
};
Plotly.newPlot(node.children[0], data, layout, { locale: 'de-DE' });
console.log(Plotly.BUILD);
I managed it like that:
var beginDate = new Date (Math.min.apply(Math, values.map(function (o) { return o.xvalue; })));
var endDate = new Date (Math.max.apply(Math, values.map(function (o) { return o.xvalue; })));
var minValue = Math.min.apply(Math, values.map(function (o) { return o.yvalue; }));
var maxValue = Math.max.apply(Math, values.map(function (o) { return o.yvalue; }));
const sortedValues = values.sort((a, b) => a.xvalue - b.xvalue);
buttonsDates=[];
first = beginDate.getFullYear();
end = endDate.getFullYear();
buttonsDates.push({
label: 'Alle Jahre', method: 'relayout',args: [
{
'xaxis.range': [beginDate,endDate]
}
]
});
for(i = first; i <= end; i++) buttonsDates.push({
label: i, method: 'relayout',args: [
{
'xaxis.range': [new Date(i,0),new Date(i,12)]
}]
});

One y axis data point there but it's x axis data point missing in weekly chart

Here below code plase any look if they know thank you.
In it 1 weeks (5 day) data points excluding saturday and sunday but x
axis 1 days (21 may) data point missing.
2 seris of data both series contain date and price in itlike share price value for that day
In attachment all x data point showing but all not distributed equally i don,t want like this img
var series_a = [{"close":1814,"date":"2021\/05\/19"},{"close":1772,"date":"2021\/05\/20"},{"close":1752,"date":"2021\/05\/21"},{"close":1793,"date":"2021\/05\/24"},{"close":1817,"date":"2021\/05\/25"},{"close":1850,"date":"2021\/05\/26"}];
var series_b = [{"close":1764,"date":"2021\/05\/19"},{"close":1752,"date":"2021\/05\/20"},{"close":1787,"date":"2021\/05\/21"},{"close":1791,"date":"2021\/05\/24"},{"close":1790,"date":"2021\/05\/25"},{"close":1804,"date":"2021\/05\/26"}];
tickDataPoint = series_b.map(function(e) {
return new Date(e.date).getTime()
});
series_a = series_a.map(function(e) {
return [new Date(e.date).getTime(), e.close, ]
});
series_b = series_b.map(function(e) {
return [new Date(e.date).getTime(), e.close, ]
});
const timezone = new Date().getTimezoneOffset()
Highcharts.setOptions({
global: {
timezoneOffset: timezone
}
});
var a = Highcharts.stockChart('dips_stock_div_aptech', {
chart: {
width: 790,
height: 280,
},
scrollbar: {
enabled: false
},
yAxis: {
opposite: false,
},
credits: {
enabled: false
},
plotOptions: {
// line: {
// dataLabels: {
// enabled: true
// },
// enableMouseTracking: false
// // }
// series: {
// gapSize: 12
// }
},
xAxis: {
// ordinal:true,
type: 'datetime',
// gridLineWidth: 1,
// tickInterval: null,
// step: 1,
// alignTicks:true,
tickInterval: 1 , // 2 month
// tickWidth:0,
// categories: tickDataPoint, tickInterval: 1,
breaks: [{
from: 1621535400000,
to: 1621708200000,
// breakSize: 1
}],
labels: {
formatter: function () {
// return Highcharts.dateFormat('%m-%e-%Y', this.value)
const index = tickDataPoint.findIndex(tickDataPoint => tickDataPoint == this.value);
console.log(tickDataPoint+'-------'+this.value); // 3
console.log(index); // 3
if (index>=0){
return Highcharts.dateFormat('%e\'%b', this.value);
}else{
return '';
}
}
}
},
rangeSelector: {
enabled: false
},
legend: {
enabled: false
},
series: [{
name: "Astral Ltd",
data: series_a,
},
{
name: "BSE Sensex",
data: series_b,
}
],
navigator: {
enabled: false
},
});
<HTML>
<BODY bgcolor="#FFFFFF">
<div id="dips_stock_div_aptech" style="overflow: visible;width:100%;margin:10px;margin-top: -5px;"></div>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
</BODY>
</HTML>
[![in img all data points showing but x data point not distributed equally date 22 and 23 may taking long space][1]][1]

not able ot show date in x axis in highcharts

i want to show date in x asis but not able to show. showing values like this 00.00.00.100 in the graph.unable to convert 1577844000000 to proper date,month,year in javascript to show in the x axis using dateTimeLabelFormats in highcharts.how to use ticks and how to show it in graphs.
ticks values are printing in the console like this.
sample tick data
1577844000000
1577843100000
1577842200000
1577841300000
15778404000
sample data from the response
DeviceTimeStamp: "2020-01-10T00:30:00"
code
getalldata();
function getalldata() {
var xhttp_roomlogs = new XMLHttpRequest();
xhttp_roomlogs.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp_roomlogs.responseText);
var Ch1Temp = [];
var Ch2Temp = [];
$(response).each(function (i, item) {
var date = UtcToIst(item.DeviceTimeStamp);
var ticks = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
Ch1Temp.push([ticks, item.Ch1Temp])
Ch2Temp.push([ticks, item.Ch2Temp])//
});
$('#container').empty();
var labels = response.map(function (e) {
var roomtempdata = e.Ch1Temp;
return parseFloat(roomtempdata);
})
var ch2temp = response.map(function (e) {
var roomtempdata = e.Ch2Temp;
return parseFloat(roomtempdata);
})
Highcharts.chart('container', {
credits: {
enabled: false
},
title: {
text: 'Chamber 1 & 2 Temp'
},
subtitle: {
text: 'in Degree Celcius'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Temperature'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
//y co-ordinates
series: [{
name: 'Chamber 1 Temp',
data: labels
},
{
name: 'Chamber 2 Temp',
data: ch2temp
}
],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
//highcharts end
}
};
xhttp_roomlogs.open("GET", "/api/data", true);
xhttp_roomlogs.send();
}
function UtcToIst(data) {
var dt = new Date(data);
return dt;
}
You can convert the json date using:
var jsonDate = "\/Date(1577844000000)\/".substr(6);
var dateObject = new Date(parseInt(jsonDate ));
var stringDate = (dateObject.getMonth() + 1) + "/" + dateObject.getDate() + "/" + dateObject.getFullYear();
console.log("Dat Object:" + dateObject);
console.log("String Date:" + stringDate);
sample hightchart code:
Highcharts.chart('container', {
chart: {
type: 'column'
},
xAxis: {
categories: ['1/1/2020', '1/2/2020', '1/3/2020', '1/4/2020', '1/5/2020']
},
plotOptions: {
column: {
stacking: 'normal'
}
},
legend: {
labelFormatter: function () {
if(this.data.length > 0) {
return this.data[0].category;
} else {
return this.name;
}
}
},
series: [{
data: [{x:0,y:1}],
name: '1/1/2020'
},{
data: [{x:1,y:1}],
name: '1/2/2020'
},{
data: [{x:2,y:1}],
name: '1/3/2020'
},{
data: [{x:3,y:1}],
name: '1/4/2020'
},{
data: [{x:4,y:1}],
name: '1/5/2020'
}]
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<figure class="highcharts-figure">
<div id="container"></div>
</figure>

Highcharts set xAxis values starting 12am and ends in 11pm

I'm using a highcharts plugin, my aim is to draw a graph for the wholeday by hour.
How to set the xAxis to use 12hour format (w/ AM&PM), start => end of the day. Or some option to have 3hours interval.
For example i have filter for today & yesterday
My Data, looks like this (timestamp & value):
[ [1561593600000, 102.5], [1561658400000, 177.45] ]
Heres my full script:
$(function(){
var moneySign = "$";
Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});
// Sales Chart
var SalesChart = Highcharts.chart('ba-chart-sales', {
title: { text: '' },
exporting: { enabled: false },
subtitle: { text: '' },
yAxis: {
title: { text: '' },
useHTML: true,
labels: {
formatter: function() {
return moneySign + this.axis.defaultLabelFormatter.call({
axis: this.axis,
value: this.value
});
}
}
},
xAxis: {
// Default for 7days & 30days (will change for today||yesterday)
type: 'datetime',
dateTimeLabelFormats: { day: '%b %e' },
tickInterval: 24 * 3600 * 1000 // interval of 1 day
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
enabled:false
},
tooltip: {
dateTimeLabelFormats: { day: '%B %e, %Y' },
shared: true,
useHTML: true,
headerFormat: '{point.key}<div>',
pointFormat: '<div style="background-color: #0549d1; height: 10px; width: 10px; border-radius: 50%; display: inline-block;"></div>' +
'<div style="margin-left: 5px; margin-top: 8px; width:30px; display: inline-block;"><b> ' + moneySign + '{point.y}</b></div>',
footerFormat: '</div>',
crosshairs: {
color: '#ccc',
className: 'chart-crosshair',
dashStyle: 'solid',
width: 1
}
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
marker: {
enabled: false,
symbol: 'circle'
}
}
},
series: [{
tooltip: { xDateFormat: '%B %e, %Y' },
showInLegend: false,
name: '',
data: []
}],
responsive: rules: [{
condition: {
maxWidth: 600
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}],
credits: { enabled: false }
});
// Initial
var SalesChartExtremes = SalesChart.yAxis[0].getExtremes();
// Change Cart Type `line` || `column`
function reDrawChart(filter, chart) {
var series = SalesChart.series[0];
var newType = ['today', 'yesterday'].includes(filter) ? 'column' : 'line';
series.chart.addSeries({
type: newType,
name: series.name,
color: series.color,
data: series.options.data,
}, false);
series.remove();
}
// Get Offer Analytics Data
function getAnalytics(filter=''){
$.ajax({
type: "GET",
url: "<%= analytics_url %>",
data: {chart_filter: filter},
dataType: "JSON",
success: function(data){
var todayLocalDate = "<%= #local_time.strftime("%Y-%m-%d") %>".split('-').map(Number);
var yesterdayLocalDate = "<%= #local_time.yesterday.strftime("%Y-%m-%d") %>".split('-').map(Number);
if( ['30', '7', ''].includes(filter) ){
var toolTipProp = { xDateFormat: '%B %e, %Y' };
var pointIntervalProp = 24 * 3600 * 1000; // one day
var pointStartProp = '';
var chartType = 'line';
}else{
if (filter == 'today'){
var pointStartProp = Date.UTC(todayLocalDate[0], todayLocalDate[1], todayLocalDate[2]);
}else if (filter == 'yesterday'){
var pointStartProp = Date.UTC(yesterdayLocalDate[0], yesterdayLocalDate[1], yesterdayLocalDate[2]);
}
var toolTipProp = { xDateFormat: '%B %e, %Y %I:%M%p' };
var pointIntervalProp = 3600000 * 3; // 3 hours
var chartType = 'column';
}
var markerEnabled = data.sales.length == 1
var salesOpts = {
tooltip: toolTipProp,
data: data.sales,
animation: { duration: 1000 },
pointInterval: pointIntervalProp,
pointStart: pointStartProp,
crosshair: true,
marker: {
enabled: markerEnabled
}
}
// Sets yAxis min & max values for empty result
if(data.sales.length == 0){
SalesChart.yAxis[0].setExtremes(0,100);
SalesChart.yAxis[0].update({tickInterval: 20});
}else{
// return to previous categories based on data
SalesChart.yAxis[0].setExtremes(SalesChartExtremes.min, SalesChartExtremes.max);
SalesChart.yAxis[0].update({tickInterval: 500});
}
if(filter == 'today' || filter == 'yesterday'){
var defaultTimeOpt = {
tickInterval: 1,
type: 'datetime',
dateTimeLabelFormats: {
millisecond: '%l:%M:%S.%L %P',
second: '%l:%M:%S %P',
minute: '%l:%M %P',
hour: '%l:%M %P',
day: '(%e. %b) %l:%M %P'
}
}
SalesChart.xAxis[0].update(defaultTimeOpt, true);
}else{
// return to day options
var defaultDayOpt = {
type: 'datetime',
dateTimeLabelFormats: { day: '%b %e' },
tickInterval: 24 * 3600 * 1000 // interval of 1 day
}
SalesChart.xAxis[0].update(defaultDayOpt, false);
}
SalesChart.series[0].update(salesOpts, true);
reDrawChart(filter, 'sales');
},
error: function(data) {
flashError("Error getting analytics");
}
});
return false;
}
});
// Call getAnalytics when select dropdown filter change (e.g. today, yesterday, lastweek ...)
getAnalytics();
Current progress,
TODO 1: If only have few data, the time where NO data should have 0 value (so there's still progress in chart).
TODO 2: Set the time/hour in xAxis & have an option for hour gap/interval like 3hours ... 12AM, 3AM, 6AM ....
If you already have the value then you can do something like
xAxis: {
labels: {
//isPm() is a function that checks for am and pm of your timestamp
format: '{value} ' + (isPm() ? "pm":"am")
}
}
also you need to show how you are plotting the chart so as to know the best way of implementation
You can change your datetime label format (API):
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
millisecond: '%l:%M:%S.%L %P',
second: '%l:%M:%S %P',
minute: '%l:%M %P',
hour: '%l:%M %P',
day: '(%e. %b) %l:%M %P',
}
}
See this JSFiddle demonstration.
The values set in dateTimeLabelFormats is a subset of PHPs strftime. In this case:
%l: Hour in 12-hour format, with a space preceding single digits. 1 through 12
%P: Lower-case 'am' or 'pm' based on the given time. Example: am for 00:31, pm for 22:23

Bind highstock(highcharts) to live data?

I am using .net core 2.0 web socket to generate some data. I want to send the data to this chart and draw the chart.
In the code below I want to show the live data without default values. I tried a lot but I wasn't successful. If I remove default value from 'series', chart will disappear. IS that possible to draw this chart on the fly?
Highcharts.setOptions({
global: {
useUTC: false
}});
Highcharts.stockChart('container', {
chart: {
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title: {
text: 'Live random data'
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -999; i <= 0; i += 1) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
}())
}]});
Finally I could find the solution. I needed to add xAxis property to my chart. By adding the code below, problem solved. Now it starts from current time.
xAxis: {
type: 'datetime',
tickPixelInterval: null,
maxZoom: 10 * 1000,
min: new Date().getTime()
}

Categories

Resources