使用谷歌应用脚本解析日期字符串 [英] Parsing date strings using google apps script
问题描述
我对Google应用程序脚本很陌生,在解析UiApp表单中的日期字符串时遇到问题。在这种情况下,我正在编写一个脚本,允许用户过滤指定日期范围内的时间戳电子表格。
我的问题是,下面的代码在传递日期字符串时(从名为 dateFromField $ c $的文本框中返回无效日期对象(例如,
2012,1,2
)的传统JavaScript格式 YYYY,M,D
2012):
function dateFilter(e){
var fromDate = new Date(e.parameter.dateFromField);
}
我检查过 e.parameter。 dateFromField
正确返回给定的字符串( Logger.log(e.parameter.dateFromField);
返回 2012,1,2
),并且它的类型是字符串(而不是对象)。
但是,如果我直接将日期字符串键入到函数中,即:
function dateFilter(e){
var fromDate = new Date(2012,1,2);
}
我得到有效的日期对象。我不明白这两个例子之间的区别 - 据我所知他们是相同的;在这两个例子中,字符串 2012,1,2
被传递给 new Date
函数。我很明显缺少一些简单的东西 - 任何人都可以告诉我是什么?解析方案
当你手工输入时,你实际上传递了3个数字参数,而不是以逗号分隔的数字列表的字符串。
我想你可以在传递之前拆分参数,例如
var dateParts = e.parameter.dataFromField.split(',');
var fromDate = new Date(dateParts [0],dateParts [1],dateParts [2]);
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?
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]);
这篇关于使用谷歌应用脚本解析日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!