[英]How to format JavaScript timestamp for Google Sheets?
How can I convert a timestamp (in milliseconds since epoch) using JavaScript into a date and time format that is useable by Google Sheets Timeline chart.如何使用 JavaScript 将时间戳(自纪元以来的毫秒数)转换为 Google 表格时间线图表可用的日期和时间格式。
My first attempt was to map the timestamps using timestamps.map(timestamp => new Date(timestamp).toLocaleString())
, but Google Sheets is not accepting this as a valid date and time format:我的第一次尝试是 map 使用
timestamps.map(timestamp => new Date(timestamp).toLocaleString())
的时间戳,但 Google 表格不接受这是有效的日期和时间格式:
I believe your current situation and goal as follows.我相信你目前的情况和目标如下。
[{timestamp: 1617413162282, value: 1}, {timestamp: 1617413239904, value: 2}].map(el => `${new Date(el.timestamp).toLocaleString()}\t${el.value}`).join("\n")
.[{timestamp: 1617413162282, value: 1}, {timestamp: 1617413239904, value: 2}].map(el => `${new Date(el.timestamp).toLocaleString()}\t${el.value}`).join("\n")
。 The values of timestamp
and value
are put to the columns "A" and "B", respectively. timestamp
和value
的值分别放在“A”和“B”列。timestamp
as the date object.timestamp
值作为日期 object。 In your situation, the values of timestamp
are put as the string.在您的情况下,
timestamp
的值被放置为字符串。 I thought that this might be the reason of your issue.我认为这可能是您的问题的原因。 In this case, in order to put the values of
timestamp
as the date object, I would like to propose to put the values using Google Apps Script.在这种情况下,为了将
timestamp
的值作为日期 object,我想建议使用 Google Apps 脚本来放置这些值。 When Google Apps Script is used, the values of timestamp
can be put as the date object.使用 Google Apps Script 时,
timestamp
的值可以设置为日期 object。 The sample script is as follows.示例脚本如下。
Please copy and paste the following script to the script editor of Google Spreadsheet you want to use.请将以下脚本复制并粘贴到您要使用的 Google 电子表格的脚本编辑器中。 And, please set the variables of
ar
and sheetName
, and run the function of myFunction
with the script editor.并且,请设置
ar
和sheetName
的变量,并使用脚本编辑器运行myFunction
的 function。 By this, the values are put to the sheet of sheetName
.这样,这些值就会被放入
sheetName
的工作表中。 In this case, the values of timestamp
are put as the date object.在这种情况下,
timestamp
的值被放置为日期 object。
function myFunction() {
const ar = [{timestamp: 1617413162282, value: 1}, {timestamp: 1617413239904, value: 2}]; // Please set the values you want to put.
const sheetName = "Sheet1"; // Please set the sheet name of the sheet you want to put the values.
const values = ar.map(({timestamp, value}) => [new Date(timestamp), value]);
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
sheet.getRange(1, 1, values.length, values[0].length).setValues(values);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.