Problem: Spreadsheet isn't recognizing an input date as a Date(), so I can't get the .getTime() from it in Apps Script.
Question: Can you see why this is?
Results: Here is a part of the script I'm running:
dates.map(function(inp) {
if (inp != undefined && inp !== ""){
inp = new Date(inp.getTime() - (date.getTimezoneOffset()*60000);
return inp
}
});
where dates
refers to a range: dates = sheet.getRange(2,1, lastR, 1).getValues();
Currently this range has a manually inputed value of "2017-05-20" which Spreadsheet automagtically recognizes as the date "Sat May 20 2017 00:00:00 GMT+0200 (CEST)"
The error reads as follows:
TypeError: Cannot find function getTime in object Sat May 20 2017 00:00:00 GMT+0200 (CEST). (line 86, file "Code") Details Dismiss
I have tried a million ways throughout my script to get Spreadsheet to stop autoconverting the input values as dates, so that I can make then at least timestamps or something. Does any one know why it is doing this?
Even if you call getValues()
on a one-column range it will still be an array of arrays.
What's confusing here is that GAS tries to be helpful and displays the only value in the one-element array.
Extracting the first element from the row should fix this issue.
dates.map(function(row) {
var inp = row[0];
if (inp != undefined && inp !== ""){
inp = new Date(inp.getTime() - (date.getTimezoneOffset()*60000);
return inp
}
});
If you insist on doing everything via Array.prototype.map(), the following code might work. I ignored your date manipulation logic, adding 5 days to the date in the cell instead. For the values to update, you must assign whatever Array.prototype.map() returns to a variable. Also, 2 separate checks for empty string and 'undefined' are redundant as JavaScript actually considers them both to be 'false' (Unfortunately, this applies to 0 as well, so be careful)
function getDates() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange(2, 1, sheet.getLastRow() - 1, 1);
var values = range.getValues();
var newValues = values.map(function(row) {
var newRow = row.map(function(value){
if (value){
value = new Date(value.getTime() + 3600000*24*5) // adding 5 days
return value;
}
});
return newRow;
});
range.setValues(newValues);
}
I ended up taking Robin's recommendation, and did the following, which worked:
rows.map(function(r) {
r.day = new Date(r.day.getTime() - (date.getTimezoneOffset()*60000));
r.day = r.day.toISOString().split('T')[0];
return r
})
where date was globally defined as date = new Date()
, "rows" the rows which have data in them, and "day" is the column name (of the first row [0] I had defined earlier in the script) for the column of dates I was trying to change.
Thanks again!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.