What is the proper syntax for formatting date on spreadsheets? - javascript

I have been reading about sheet formats. I am using fetch and tokens to write data.
rows: [{
values: [
{
userEnteredValue: { numberValue: Math.round(new Date().getTime() / 1000) },
userEnteredFormat: {
numberFormat: {
type: 'DATE', pattern: 'ddd dd hh:mm'
}
}
}],
fields: 'userEnteredValue, userEnteredFormat'
}]
After posting the data when I click on the cell a calender shows but the time shown in not in the correct format its in epoc

In this case, it is required to convert from the Unix time to the serial number. And, I think that type might be type: "DATE_TIME". When these points are reflected in your showing script, how about the following modification?
Modified script:
var unixTime = new Date().getTime();
var serialNumber = (unixTime / 1000 / 86400) + 25569; // Ref: https://stackoverflow.com/a/6154953
var requests = {
requests: [{
updateCells: {
rows: [{ values: [{ userEnteredValue: { numberValue: serialNumber }, userEnteredFormat: { numberFormat: { type: "DATE_TIME", pattern: "ddd dd hh:mm" } } }] }],
range: { sheetId: 0 },
fields: "userEnteredValue, userEnteredFormat",
}
}]
};
In this cacse, the value is put into the cell "A1" of the sheet ID 0.
References:
Method: spreadsheets.batchUpdate
NumberFormatType

Related

Cannot format date time in chart.js - vanilla js

I trying to display date in this format: "YYYY-MM-DD HH:mm", But when I trying like this:
const formatDate = "YYYY-MM-DD HH:mm";
mikeFWLabelChart = moment(mikeFWLabelChart).format(formatDate);
const a = new Chart(canvasElement, {
data: {
labels: mikeFWLabelChart,
datasets: [{
type: 'line',
label: 'Метра',
data: mikeFWDataChart,
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
type: "time",
time: {
format: formatDate,
tooltipFormat: 'll'
},
scaleLabel: {
display: true,
labelString: 'Date'
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value'
}
}]
}
}
})
};
I receive error on X axis INVALID DATE..
Also I trying to change format date without moment code:
mikeFWLabelChart = moment(mikeFWLabelChart).format(formatDate);
with options code -> format But they still look like this format: 2023-02-16T05:00:00.000Z
How to change date format in this YYYY-MM-DD HH:mm ?
With moment.js you do it like this:
const formatDate = "YYYY-MM-DD HH:mm";
const date = new Date("2023-02-16T05:00:00.000Z");
const formattedDate = moment.utc(date).format(formatDate);
console.log(formattedDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
With .toISOString() you do it like this:
const date = new Date("2023-02-16T05:00:00.000Z").toISOString();
const formattedDate = date.slice(0, 16).replace("T", " ");
console.log(formattedDate);

is it possible to have 2 data sets on single line chart in chart.js?

Preview:
I am using chart.js in Angular 7 application. I want to know, is it possible to have 2 data sets on single line chart.
Detail:
On my X-axis I have time related data and Y-axis contains numbers. Based on API response, (which returns time stamp and number) I can generate a line chart. But I want to have 2nd datasets on same line. 2nd data set related API response, gives me time stamp, so I want to use that time stamp to project point (maybe of different color) to show on single line.
this.chart = new Chart(ctx, {
type: 'line',
data: this.getChartAxisData(),
options: this.getChartOptions()
});
getChartAxisData() {
const first: any[] = this.listOne.map((data) => (new Date(data.date)));
const firstArray: any[] = this.listOne.map((data) => data.number);
const second: any[] = this.listTwo.map((data) => (new Date(data.date)));
return {
labels: first,
datasets: [
{
data: firstArray
}
]
};
}
getChartOptions() {
return {
scales: {
xAxes: [{
type: 'time',
time: {
max: this.endDate,
min: this.startDate,
displayFormats: {
'millisecond': 'hh:mm A',
'second': 'hh:mm A',
'minute': 'hh:mm A',
'hour': 'hh:mm A',
'day': 'DD-MMM',
'week': 'DD-MMM',
'month': 'DD-MMM'
}
}
}],
yAxes: [{
ticks: {
min: 0,
max: 800
}
}]
}
};
}

JSON api timestamp + data parsing

I'm making a chart using Highcharts.js
The API I'm using has a different output than what Highchart uses.
Highchart reads JSON data as [timestamp, data]
which looks something like this: [1512000000000,171.85],
furthermore, the rest of the data is parsed within the same call.
Now MY Api outputs data by a single call for each timestamp (via url &ts=1511929853 for example
outputs {"ENJ":{"USD":0.02154}} (the price for that point in time)
Now here's where things get complicated. I would need to parse the price from a certain date, till now.
I've already made a ++ variable for the timestamp, but how would I include the timestamp and the price for that timestamp within the array for the data output.
It's a bit confusing, as the calls would have to be repeated so many times to draw a historical graph of the price. Some help would be appreciated. If you need more clarification, I'm right here.
Data is parsed via data function
full code here
var startDate = 1511929853;
var endDate = Math.floor((new Date).getTime()/1000);
function count() {
if (startDate != endDate) {
startDate++
}
else {
return false;
}
};
count();
$.getJSON('https://min-api.cryptocompare.com/data/pricehistorical?fsym=ENJ&tsyms=USD&ts=' + startDate, function (data) {
// Create the chart
var enjPrice = `${data.ENJ.USD}`;
console.log(enjPrice);
Highcharts.stockChart('container', {
xAxis: {
gapGridLineWidth: 0
},
rangeSelector: {
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'day',
count: 1,
text: '1D'
}, {
type: 'all',
count: 1,
text: 'All'
}],
selected: 1,
inputEnabled: false
},
series: [{
name: 'AAPL',
type: 'area',
data: JSON.parse("[" + enjPrice + "]"),
gapSize: 5,
tooltip: {
valueDecimals: 2
}
}]
});
});
You can use spread operator, like this,
let var = [new Date().getTime(), { ...data }.ENJ.USD]
This will result [1512000000000, 171.85] as you expected.
You need to make different functions for getting the data and generating the chart. Below is an example of how would you do it.
var startDate = 1511929853;
var endDate = Math.floor((new Date).getTime() / 1000);
var data = [];
function count() {
if (startDate != endDate) {
data.push(getPrice(startDate));
startDate++;
} else {
generateChart();
}
};
count();
function getPrice(timestamp) {
$.getJSON('https://min-api.cryptocompare.com/data/pricehistorical?fsym=ENJ&tsyms=USD&ts=' + startDate, function(data) {
return [timestamp, data.ENJ.USD];
});
}
function generateChart() {
Highcharts.stockChart('container', {
xAxis: {
gapGridLineWidth: 0
},
rangeSelector: {
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'day',
count: 1,
text: '1D'
}, {
type: 'all',
count: 1,
text: 'All'
}],
selected: 1,
inputEnabled: false
},
series: [{
name: 'AAPL',
type: 'area',
data,
gapSize: 5,
tooltip: {
valueDecimals: 2
}
}]
});
}
Though this is not the best way how you would do it but you get an idea.
I managed to solve the problem, by using a different API, which indexes data for past 30 days. I iterated into each index, 31, of them and grabbed the time and high(price) values and parsed them into a number since I was getting a "string" and then looped them into an array and put them into the final data [array]. just what I needed for the chart to work. If anyone needs any help just ask away. :) PS: Excuse the console.logs as I was using them to debug and test which helped me tremendously, you can remove them, as shall I
$.getJSON('https://min-api.cryptocompare.com/data/histoday?fsym=ENJ&tsym=USD', function(data) {
var x = `${data.Data[0].time}`;
var y = `${data.Data[0].high}`;
console.log(x);
console.log(y);
var tempData = [];
console.log(tempData);
for (var i = 0; i < 31; i++ ) {
var a = `${data.Data[i].time}`;
var b = `${data.Data[i].high}`;
function numberfy(val){
parseFloat(val);
}
a = parseFloat(a);
a = a * 1000;
b = parseFloat(b);
x = [a , b];
tempData.push(x);
};
data = tempData;
console.log(data.length);
Highcharts.stockChart('container', {

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
}]
}
]
});
});

Highcharts load pointStart from JSON. Milliseconds to UTC time?

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);
}

Categories

Resources