Reputation: 373
I'm trying to set a const "Yesterday" but the script is not recognised as a function (I'm using Google App Scripts). I've tried different syntax including:
const yesterday = today.setDate(-1);
and
const yesterday = new Date(today.setDate(-1));
But neither worked. I'm pretty sure it should be a minor change but I cannot figure out how to solve this. A little help would be highly appreciated, thanks !
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('My Report');
function insertColumn() {
const range = sheet.getRange('H1:H69').getValues();
const newrange = sheet.getRange('I1:I69');
const rules = sheet.getConditionalFormatRules();
const today = Utilities.formatDate(new Date(), "GMT+7", "MM/dd/yyyy");
const yesterday = new Date(today.setDate(-1));
Upvotes: 0
Views: 1708
Reputation: 147146
Your issue is that today
is not a Date
object, because you've called Utilities.formatDate
on it. This is why you are getting an error when trying to use today.setDate()
. So you need to use another variable to allow you to compute yesterday
. For example:
const tmp = new Date();
const yesterday = new Date(tmp.setDate(tmp.getDate()-1))
Also note that setDate(-1)
sets the date to the penultimate day in the previous month (e.g. March 30 when you are in April), you need to get the current date (using getDate
) and subtract 1 from that to get yesterday's date.
Upvotes: 2
Reputation: 64032
function yesterday() {
let dt = new Date();
Logger.log(new Date(dt.setDate(dt.getDate() - 1)));
}
From MDN setDate() returns: The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date... not a date object
Upvotes: 0
Reputation: 1
getYesterday() {
let date = new Date();
let yesterday_milliseconds = date.getTime() - 1000 * 60 * 60 * 24;
let yesterday = new Date();
yesterday.setTime(yesterday_milliseconds);
let strYear = yesterday.getFullYear();
let strDay = yesterday.getDate();
let strMonth = yesterday.getMonth() + 1;
if (strMonth < 10) {
strMonth = "0" + strMonth;
}
if (strDay < 10) {
strDay = "0" + strDay;
}
return strYear + "-" + strMonth + "-" + strDay;
},
Upvotes: 0