xecgr
xecgr

Reputation: 5193

Date object's type differs type between manual/scheduled execution = Cannot find method formatDate((class),string,string)

I've been facing an extrange issue with google scripts. Bellow the easy-to-understand snippet:

//https://stackoverflow.com/a/7390612/2873381
function typeOf(obj) {
  return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
function run(working_day){
  if (!working_day){
     working_day = new Date();
  }
  console.log("working_day");
  console.log(typeOf(working_day));
  console.log(working_day);
  var timeZone   = Session.getTimeZone();
  var curr_day   = Utilities.formatDate(working_day, timeZone, "F");
  var curr_hour  = Utilities.formatDate(working_day, timeZone, "H");
  console.log(curr_day);
  console.log(curr_hour);
}

This snippet get now if no working_day is provided. Once it has a valid instance of Date it tries to get week-day and current-hour using Utilities handy functions.
If I run this snippet manually from Editor, there's no problem, output is the expected . ok
However, If I set a crontab execution, say every hour, this code raises an error ko
The weirdest point here is the unexpected javaobject value, I don't know why working_day gets this instance type....
Can you help me? Thanks

Upvotes: 1

Views: 41

Answers (1)

Cooper
Cooper

Reputation: 64100

Presumably your function run() calls some other function which requires the timezone, current day of the week and current hour. In this situation because of the way the trigger reports day-of-week I'd probably just avoid using the event object altogether and do it this way.

function run(){
  var dt=new Date();
  var timeZone   = Session.getScriptTimeZone();
  var curr_day   = dt.getDay();//0=Sunday 6=Saturday 
  var curr_hour  = dt.getHours();0-23
  Logger.log('%s,%s,%s',timeZone,curr_day,curr_hour);
}

And so it will run the same way whether is triggered via a timer based trigger or if you run it manually. It will take a little longer but not that much.

Upvotes: 2

Related Questions