[英]How to convert Date (from google sheet data) to TimeStamp (Firestore) using AppScript?
I've got a date object in Google Sheet which I want to import to firestore as a timestamp object, but it doesn't work when I do it directly.我在 Google 表格中有一个日期 object,我想将它作为时间戳 object 导入到 Firestore,但是当我直接执行时它不起作用。
If I enter the current date,
如果我输入当前日期,
data.date = new Date(dateSt);
it stores an empty map object in firestore.它在 Firestore 中存储了一个空的 map object。
What should I do to convert the date object to timestamp.我应该怎么做才能将日期 object 转换为时间戳。
Full Code:完整代码:
function classRoutineFunction() {
const email = "my_email";
const key = "my_private_key";
const projectId = "my_projectID";
var firestore = FirestoreApp.getFirestore (email, key, projectId);
// get document data from ther spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetname = "Sheet1";
var sheet = ss.getSheetByName(sheetname);
// get the last row and column in order to define range
var sheetLR = sheet.getLastRow(); // get the last row
var sheetLC = sheet.getLastColumn(); // get the last column
var dataSR = 2; // the first row of data
// define the data range
var sourceRange = sheet.getRange(2,1,sheetLR-dataSR+1,sheetLC);
// get the data
var sourceData = sourceRange.getValues();
// get the number of length of the object in order to establish a loop value
var sourceLen = sourceData.length;
// Loop through the rows
for (var i=0;i<sourceLen;i++){
if(sourceData[i][1] !== '') {
var data = {};
var dateSt = sourceData[i][0].toString();
var stDate = new Date(dateSt);
var stringfied = JSON.stringify(stDate);
var updatedDt = stringfied.slice(1,11);
data.date = new Date(dateSt);
data.time = sourceData[i][1];
data.batch = sourceData[i][2];
data.topic = sourceData[i][3];
firestore.createDocument("classRoutine",data);
}
}
}
Make sure your date value is a dates
and not a String
.确保您的日期值是
dates
而不是String
。 Use DATEVALUE
to convert a String to a date the FirestoreApp can interpret as a timestamp.使用
DATEVALUE
将字符串转换为 FirestoreApp 可以解释为时间戳的日期。
Bonus: If you use =DATEVALUE('2020-07-11') + TIMEVALUE('18:00:00)
it will add the time to the timestamp in Firestore.奖励:如果您使用
=DATEVALUE('2020-07-11') + TIMEVALUE('18:00:00)
它会将时间添加到 Firestore 中的时间戳。
If you are using the library by "graham" 1VUSl4b1r1eoNcRWotZM3e87ygkxvXltOgyDZhixqncz9lQ3MjfT1iKFw The bug is fixed when using version 30 for me.如果您正在使用“graham”的库 1VUSl4b1r1eoNcRWotZM3e87ygkxvXltOgyDZhixqncz9lQ3MjfT1iKFw 为我使用版本 30 时修复了该错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.