-->

Parsing date strings using google apps script

2020-07-30 03:46发布

问题:

I'm new to google apps script, and I'm having trouble parsing date strings from a UiApp form. In this instance, I'm writing a script to allow the user to filter a timestamped spreadsheet within a specified date range.

My problem is that the code below returns an invalid date object when passed a date string (from a text box named dateFromField) in the conventional javascript format YYYY,M,D (i.e. 2012,1,2 for Feb 2, 2012):

function dateFilter(e) {
  var fromDate = new Date(e.parameter.dateFromField);
} 

I've checked that the e.parameter.dateFromField correctly returns the given string (Logger.log(e.parameter.dateFromField); returns 2012,1,2), and that its type is string (rather than object).

However, if I type the date string into the function directly, i.e.:

function dateFilter(e) {
  var fromDate = new Date(2012,1,2);
} 

I get valid a date object. I don't understand the difference between these two examples - as far as I can tell they are equivalent; in both instances the string 2012,1,2 is being passed to the new Date function. I'm obviously missing something simple - can anyone tell me what?

回答1:

When you typed it manually, you actually passed 3 number parameters, not a string with a list of comma separated numbers.

I guess you could just split your parameter before passing, e.g.

var dateParts = e.parameter.dataFromField.split(',');
var fromDate = new Date(dateParts[0], dateParts[1], dateParts[2]);


回答2:

I would recommend using either the DateBox and DatePicker classes in UiApp instead of a text box. They return an actual date object therefore eliminating the need to parse at all. They were just added to the Apps Script documentation. See here.