Convert date object from Google sheets (javaScript) to Firebase time stamp using AppScript

时光总嘲笑我的痴心妄想 提交于 2020-06-09 05:20:04

问题


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.I am using JavaSript in the Appscript.

This stores an empty map in firestore:

 data.date = new Date();

What should I do to convert the date object to timestamp.

This is my full code

function uploadData() {
   var firestore = FirestoreApp.getFirestore (email, key, projectId);
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheetname = "Sheet1";
   var sheet = ss.getSheetByName(sheetname); 
   var sheetLR = sheet.getLastRow();
   var sheetLC = sheet.getLastColumn(); 
   var dataSR = 2; 
   var sourceRange = sheet.getRange(2,1,sheetLR-dataSR+1,sheetLC);
   var sourceData = sourceRange.getValues();
   var sourceLen = sourceData.length;

  // Loop through the rows
   for (var i=0;i<sourceLen;i++){
     if(sourceData[i][1] !== '') {
       var data = {};

       data.date = new Date(); //Want to convert this date to timestamp object for firestore
       data.time = sourceData[i][1];
       data.batch = sourceData[i][2];
       data.topic = sourceData[i][3];

       firestore.createDocument("classRoutine", data);
     }

  }
}

回答1:


Suppose if your date object is like 3/2/2020 9:06:07 and from that, you need to extract only the date 2020-03-02 and for that date, if you want to get the timestamp 1583087400000 you can try the below solution.

       var dateSt = sourceData[i][0].toString();
       var stDate = new Date(dateSt);
       var stringfied = JSON.stringify(stDate);
       var updatedDt = stringfied.slice(1,11);

       //now u will have the date as 2020-03-02

       var myDate= updatedDt;
       myDate=myDate.split("-");
       var formattedDate=myDate[0]+"/"+myDate[1]+"/"+myDate[2];

       //Now the date is converted to 2020/03/02 (it should be in YYYY/MM/DD)

       var timestamp = new Date(formattedDate).getTime();

       //Now will have the timestamp for that particular date as 1583087400000
       data.date = timestamp;

Suppose if u don't have a date in your google sheet and you want to create it from the app script means you can try this second solution

       var dateSt = new Date().toISOString().slice(0,10);
       //dateSt will have the date in 2020-06-04
       var myDate = dateSt;
       myDate = myDate.split("-");
       var formattedDate=myDate[0]+"/"+myDate[1]+"/"+myDate[2];
       //formatted date will be 2020/06/04
       var timestamp = new Date(formattedDate).getTime();
       //timeStamp will be 1591209000000
       data.date = timestamp;


来源:https://stackoverflow.com/questions/62149933/convert-date-object-from-google-sheets-javascript-to-firebase-time-stamp-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!