How to convert JSON object to datetime - javascript

I need to show JSON data in Kendo chart.
My code as follows,
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.common.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script>
</head>
<body>
<div id="chart"></div>
$("#chart").kendoChart({
series: [{
data: [new Date(formatTime(360)).getTime(), // here 360 means seconds
new Date(formatTime(100)).getTime(),
new Date(formatTime(125)).getTime(),
new Date(formatTime(146)).getTime(),
new Date(formatTime(65)).getTime(),
new Date(formatTime(185)).getTime(),
new Date(formatTime(236)).getTime(),
new Date(formatTime(100)).getTime()],
color: "Blue",
name: "Average time",
type: "line"
},
{
data: [new Date(formatTime(760)).getTime(),
new Date(formatTime(100)).getTime(),
new Date(formatTime(125)).getTime(),
new Date(formatTime(148)).getTime(),
new Date(formatTime(65)).getTime(),
new Date(formatTime(185)).getTime(),
new Date(formatTime(236)).getTime(),
new Date(formatTime(100)).getTime()],
color: "Red",
name: "Wait time",
type: "bar",
}
]
,
valueAxis: {
labels: {
template: "#= kendo.format('{0:HH:mm:ss}', new Date(value)) #"
},
min: new Date("2018/02/01").getTime(),
majorUnit: 10 * 60 * 1000 // 20 minutes step
},
tooltip: {
visible: true,
template: "#= kendo.format('{0:HH:mm:ss}', new Date(value)) #"
}
});
function formatTime(time) {
var rootDate = new Date(new Date(2018, 1, 1, 0, 0, 0).setSeconds(time));
return rootDate;
}
here you can see, I set static chart data as data: [new Date(formatTime(360)).getTime()] I need to set dynamic JSOn object to chart data from JSON object.
I have the following JSON object.
[{
day: "YYY",
second: "100",
second2: "125"
}, {
day: "XXX",
second: "145",
second2: "117"
}, {
day: "TTT",
second: "565",
second2: "340"
}, {
day: "SSS",
second: "125",
second2: "250"
}]
I receiving separate JSON key from backend as second and second2.I need to set those fields to Chart series as new date object. how can I do it

If you're thinking about getting a new javascript values parsing some string that contains js codes, Just run eval function and let it do it's magic. Check this code:
let x = 'new Date()';
console.log(eval(x))

Assuming that second should populate the first series (average time) and second2 the second series (wait time), you could do this:
series: [{
data: arr.map(function (o) {
return new Date(formatTime(o.second)).getTime();
}),
color: "Blue",
name: "Average time",
type: "line"
},
{
data: arr.map(function (o) {
return new Date(formatTime(o.second2)).getTime();
}),
color: "Red",
name: "Wait time",
type: "bar",
}]
...where arr is the array you get from your back-end (after conversion from JSON of course).

Related

How to format the x-axis labels in ApexCharts

I have an API that returns data like this:
[
{
"attributes": {
"type": "AggregateResult"
},
"expr0": 25937961.52,
"expr1": 1,
"expr2": 2020
},
{
"attributes": {
"type": "AggregateResult"
},
"expr0": 4092447.85,
"expr1": 3,
"expr2": 2020
},
{
"attributes": {
"type": "AggregateResult"
},
"expr0": 18509414.84,
"expr1": 6,
"expr2": 2019
},
{
"attributes": {
"type": "AggregateResult"
},
"expr0": 13572118.12,
"expr1": 10,
"expr2": 2019
},
...
Where expr0 is an monetary value, expr1 is the month and expr2 is the year. I am using ApexCharts in React to display the results on my website, however I can't seem to format the data correctly. My component is shown below, however it currently only displays a single point. I'm not sure whether the data points need x/y keys to be displayed or if the dates need to be in the x-axis in options.
class SFAllTimeQuoteValue extends Component {
constructor(props) {
super(props);
this.state = {
series: [{
name: "Opportunities",
data: []
}],
options: {
chart: {
id: "line"
},
xaxis: {
type: "date"
}
}
}
}
async componentDidMount() {
var res = await axios.get(api);
const value = res.data;
var data = [];
for(var i = 0; i < value.length; i++) {
var date = new Date(value[i].expr2, value[i].expr1 - 1);
data.push([date, value[i].expr0]);
}
this.setState({
series: [{
data: data
}]
})
}
render() {
return (
<div>
<Chart series={this.state.series} type ='line' options ={this.state.options}/>
</div>
)
}
}
I would preferably like the data points to display just the month and year as the label too, however using my current method I am getting full date time strings as the label.
You should set the xaxis type as datetime and also set the labels.format property
xaxis: {
type: 'datetime',
labels: {
format: 'MM yyyy'
}
}

Highcharts: create multiple series grouped my month and year using JSON data

I am trying to create a line, spline chart using JSON data. I want multiple series but I am confused on how to do that. Right now I am able to create the multiple series when the date is in 2019-07-06 format. I also have a JSON that has a column for the month and a column for the year Please help on how I can fix this. Right now I only have the code for group by day.
JSON Data:
[
{ "month": 6,
"year": 2019,
"starts": 21278998,
"completes": 9309458
},
{ "month": 7,
"year": 2019,
"starts": 38850115,
"completes": 17790105
}
]
I used the solution for the date format 2019-07-06 provided in this fiddle: https://jsfiddle.net/BlackLabel/tjLvh89b/
Please help with how I can create a chart for the Month, Year on the x-Axis.
You can achieve it simply by creating a Date object using different parameters.
Instead of the string date parameter new Date('2019-07-07') use year and month as separate parameters like that: new Date(2019, 7).
Code:
var json = [{
month: 6,
year: 2019,
starts: 21278998,
completes: 9309458
}, {
month: 7,
year: 2019,
starts: 38850115,
completes: 17790105
}];
var series1 = {
name: 'starts',
data: []
},
series2 = {
name: 'completes',
data: []
};
json.forEach(elem => {
series1.data.push({
x: +new Date(elem.year, elem.month),
y: elem.starts
});
series2.data.push({
x: +new Date(elem.year, elem.month),
y: elem.completes
});
});
Highcharts.chart('container', {
chart: {
type: 'spline'
},
xAxis: {
type: 'datetime'
},
series: [
series1,
series2
]
});
Demo:
https://jsfiddle.net/BlackLabel/xtefuLsp/1/
Date object reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

How to dynamically add stockEvents to amCharts

I have a function I'm using to add new data points to my stock chart. I need to create a condition under which one of the data points comes with an icon. I see that stockEvents can do this but it's not showing in my chart:
function addDataPoint(ask) {
var dataProvider = chart.dataSets[0].dataProvider;
var newDate = new Date(dataProvider[dataProvider.length - 1].date.getTime());
newDate.setHours(newDate.getHours(), newDate.getMinutes() + 1, newDate.getSeconds());
var a = Math.round(Math.random() * (40 + 1000)) + 100 + 1000;
var b = Math.round(Math.random() * 100000000);
dataProvider.push({
date: newDate,
value: ask,
volume: ask
});
chart.dataSets[0].stockEvents = [{
date: newDate,
type: "flag",
text: "F",
description: "Some longer\ntext can also\n be added"
}];
dataProvider.shift();
}
You need to set the stock event's graph property in order for it to be visible. This can be a reference to the stock graph object, or the graph's id. You also need to call validateData in order to update the chart if you aren't already doing so outside of your addDataPoint function.
AmCharts.makeChart("chartdiv", {
// ...
"panels": [{
// ...
"stockGraphs": [{
// ...
"id": "g1", //added id
// ...
},
// ...
]
},
// ...
],
// ...
});
// ...
function addDataPoint(ask) {
// ...
chart.dataSets[0].stockEvents = [{
date: newDate,
type: "flag",
text: "F",
graph: "g1", //added
description: "Some longer\ntext can also\n be added"
}];
dataProvider.shift();
chart.validateData(); //added
}
Also note that you're overwriting the stockEvents array each time in your addDataPoint function. If you want to preserve your previous event, then you need to use push since it's an array.
Demo

Real Time Chart Generation using epoch.js

I am trying to create a simple real time chart using epoch.js which updates itself on a click event.
My code posted below has a total of 3 functions. They are:
1) generate a random value
2) generate the current date and time in milliseconds.
3) onclick event that updates chart datapoints.
Though I have datapoints in the right format as required for the chart. I am unable to update it .
Appreciate any help on find out as to why the graph is not working as it should.
///////////////this function generates the date and time in milliseconds//////////
function getTimeValue() {
var dateBuffer = new Date();
var Time = dateBuffer.getTime();
return Time;
}
////////////// this function generates a random value ////////////////////////////
function getRandomValue() {
var randomValue = Math.random() * 100;
return randomValue;
}
////////////// this function is used to update the chart values ///////////////
function updateGraph() {
var newBarChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
barChartInstance.push(newBarChartData);
}
////////////// real time graph generation////////////////////////////////////////
var barChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
var barChartInstance = $('#barChart').epoch({
type: 'time.bar',
axes: ['right', 'bottom', 'left'],
data: barChartData
});
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js">
</script>
<script src="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/d3.min.js">
</script>
<script src="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/epoch.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/epoch.min.css">
</head>
<div id="barChart" class="epoch category10" style="width:320px; height: 240px;"></div>
<p id="updateMessage" onclick="updateGraph()">click me to update chart</p>
You are pushing the wrong object to barChartInstance when updating the graph. You need to just push the array containing the new data point, instead of pushing the full configuration again.
function updateGraph() {
var newBarChartData = [{time: getTimeValue(), y:getRandomValue()}];
/* Wrong: don't use the full configuration for an update.
var newBarChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
*/
barChartInstance.push(newBarChartData);
}
///////////////this function generates the date and time in milliseconds//////////
function getTimeValue() {
var dateBuffer = new Date();
var Time = dateBuffer.getTime();
return Time;
}
////////////// this function generates a random value ////////////////////////////
function getRandomValue() {
var randomValue = Math.random() * 100;
return randomValue;
}
////////////// this function is used to update the chart values ///////////////
function updateGraph() {
var newBarChartData = [{time: getTimeValue(), y:getRandomValue()}];
/*
var newBarChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
*/
barChartInstance.push(newBarChartData);
}
////////////// real time graph generation////////////////////////////////////////
var barChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
var barChartInstance = $('#barChart').epoch({
type: 'time.bar',
axes: ['right', 'bottom', 'left'],
data: barChartData
});
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js">
</script>
<script src="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/d3.min.js">
</script>
<script src="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/epoch.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/epoch.min.css">
</head>
<div id="barChart" class="epoch category10" style="width:320px; height: 240px;"></div>
<p id="updateMessage" onclick="updateGraph()">click me to update chart</p>

Date and Time value from Database to be used on axis

I am trying to add axis labels to my X axis with the date instead of just 1,2,3,4 etc. which it defaults to.
The date_time returned from the server also needs to be converted to a readable date/time.
Any help appreciated.
Code
<script type="text/javascript">
var chart;
var store;
require(["dojo/request/xhr",
"dojo/json",
"dojo/store/Memory",
"dojo/store/Observable",
"dojox/charting/StoreSeries",
"dojox/charting/Chart2D",
"dojox/charting/plot2d/Lines",
"dojox/charting/axis2d/Default",
"dojo/domReady!"],
function(xhr, JSON, Memory, Observable, StoreSeries, Chart) {
xhr("json_result.php",{
handleAs: "json"
}).then(function(data){
store = Observable(new Memory({data: data}));
chart = new Chart("graph");
chart.addPlot("default", {type: "Lines", markers:true});
chart.addAxis("x", {title:"Time", titleOrientation:"away"});
chart.addAxis("y", {vertical: true, majorTick: false, title:"Load"});
chart.addSeries("Load Cell 1", new StoreSeries(store, { query: { load_cell_id:0 }}, "kn"));
chart.addSeries("Load Cell 2", new StoreSeries(store, { query: { load_cell_id:1 } }, "kn"));
chart.render();
});
});
</script>
JSON Result
[{"date_time":1351280845,"load_cell_id":0,"kn":56.8},{"date_time":1351280845,"load_cell_id":1,"kn":45},{"date_time":1351367241,"load_cell_id":0,"kn":23.7},{"date_time":1351367241,"load_cell_id":1,"kn":34.9},{"date_time":1351417945,"load_cell_id":0,"kn":56.9},{"date_time":1351417945,"load_cell_id":1,"kn":67.8},{"date_time":1353914066,"load_cell_id":0,"kn":12.4},{"date_time":1353914066,"load_cell_id":1,"kn":19.43},{"date_time":1353992714,"load_cell_id":0,"kn":45.8},{"date_time":1353992714,"load_cell_id":1,"kn":40.8}]
Try following, its about controlling the indexes (major) and then formatting the data-date_time in a label generating function.
ddl => "dojo/date/locale", require this
chart.addAxis("x", {
title: "Time",
titleOrientation: "away",
includeZero: true,
//from: 0, to: (data.length -1),
minorTicks: false,
labelFunc: function(n){
// I am assuming that your timestamp needs to be multiplied by 1000.
var date = new Date(parseInt(data[n].date_time) * 1000);
return ddl.format(date, {
selector: "date",
datePattern: "dd MMMM"
});
}
});
The minor ticks will produce 0.1, 0.2 additions to the current major tick - and does not go well together with an array indice.

Categories