0

我有一个表单,它通过“表单提交”触发器激活程序。在这个例程结束时,我想在例程结束时插入表单的时间戳和当前时间之间的时间差(差仅几秒钟)。

到目前为止,我已经尝试了很多东西,但我通常收到的结果是 NaN。

我认为我最好的选择是构建运行时元素(H、M、S)并类似地从整个时间戳中解构时间元素,然后对其进行一些数学运算:

var rt_ts = Math.abs(run_time - ts_time);

(顺便说一句,我从这个网站的某个地方得到了那个公式,但我显然现在掌握了任何东西。我似乎无法找到解决我的特定问题的线程)

我一直发现在 Javascript 中处理日期和时间是一件棘手的事情(例如:“月”从零开始,而“日期”从 1 开始的怪癖。这不必要地令人费解)。有没有人愿意引导我摆脱目前的“掌握”心态并引导我走向类似于逻辑方法的东西?

4

2 回答 2

2

您可以简单地将其添加到 onFormSubmit 例程的顶部:

  UserProperties.setProperty('start',new Date().getTime().toString())

最后会以毫秒为单位显示持续时间。

var duration = new Date().getTime()-Number(UserProperties.getProperty('start'))

根据您的评论进行编辑:

来自 onFormSubmit 事件的时间戳是返回的数组的第一个元素,e.values请参见此处的文档

所以我真的不明白你有什么问题??

下面这样的东西应该可以工作

var duration = new Date().getTime() - new Date(e.values[0]).getTime();//in millisecs

该值是一个字符串,我将它传递给“新日期”以使其再次成为日期对象。您可以像这样使用记录器轻松检查: Logger.log(new Date(e.values[0]));//

它将以 Fri Mar 12 15:00:00 GMT+01:00 2013的形式返回完整的日期值

但是这些值很可能与我的第一个建议相同,因为时间戳是触发函数的时刻......

于 2013-04-24T19:41:43.140 回答
0

我有一个函数,它可以在 A 列中显示带有时间戳的 ss 中的时间。它还将脚本本身的时间添加到第一个时间戳(在第 3 行中)并在日志中显示。

请注意,谷歌电子表格时间戳的分辨率以秒为单位,脚本时间戳以毫秒为单位。因此,如果您只在电子表格时间戳中添加 300 毫秒,那么如果将其发布回电子表格,则可能根本不会显示任何差异。下面的脚本只需要大约 40 毫秒即可运行,因此我添加了一个 Utilities.sleep(0),您可以在其中将值 0 更改为 1000 以上以显示差异。

function testTime(){
      var start = new Date().getTime();
      var values = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
      for(var i = 2; i < values.length ; i++){
      Logger.log(Utilities.formatDate(new Date(values[i][0]),Session.getTimeZone(),'d MMM yy hh:mm:ss' )); // this shows the date, in my case same as the ss timestamp.
      Logger.log(  new Date(values[i][0]).getTime()  ); // this is the date in Milliseconds after 1 Jan 1970
      }

      Utilities.sleep(0); //you can vary this to see the effects

      var endTime = new Date();
      var msCumulative = (endTime.getTime() - start);
      Logger.log(msCumulative);
      var msTot = (msCumulative + new Date(values[2][0]).getTime());
      Logger.log('script length in milliseconds ' + msTot );

      var finalTime = Utilities.formatDate(new Date(msTot), Session.getTimeZone(), 'dd/MM/yyyy hh:mm:ss');
      Logger.log ( finalTime); //Note that unless you change above to  Utilities.sleep(1000) or greater number , this logged date/time is going  to be identical to the first timestamp since the script runs so quickly, less than 1 second.

    }
于 2013-04-24T19:20:31.727 回答