【问题标题】:How to find and replace date, on timebased trigger by using ScriptApp Custom function如何使用 ScriptApp 自定义功能在基于时间的触发器上查找和替换日期
【发布时间】:2016-01-12 14:30:15
【问题描述】:

我有一份 Google 文档,文档正文中只有一个日期。我正在尝试编写一个每 24 小时更新一次日期的脚本。

文档中的日期当前设置为“11/01/2016”作为文本,比今天(2016 年 12 月 1 日)少 1 天。我认为使用 replaceText() 会起作用。

这是我目前的脚本。

ScriptApp.newTrigger("myFunction")
.timeBased()
.atHour(24)
.everyDays(1)
.inTimezone("GMT")

function myFunction() 
{
 var date = Utilities.formatDate(new Date(), "GMT", "dd/MM/yyy"); 
 var doc = DocumentApp.openById("ID of Document");
 doc.replaceText(date-1,date) ;
}

我在这里做错了什么?

【问题讨论】:

  • 您看到的结果与您期望看到的结果是什么? “自定义功能”与这个问题有什么关系?提示:在函数外部调用.newTrigger() 是个坏主意;每次调用脚本中的任何函数时都会调用它。

标签: replace google-apps-script google-docs


【解决方案1】:

您不能替换文档对象上的文本,您需要获取文档正文。你的date 是一个字符串,你不能通过date-1 得到昨天。也参考日期转换。

function myFunction() 
{
 var body = DocumentApp.getActiveDocument().getBody();
 var d = new Date();
 var yesterdayDate = Utilities.formatDate(new Date(d.getTime()-1*(24*3600*1000)), "GMT", "dd/MM/yyy"); 
 var todayDate = Utilities.formatDate(d, "GMT", "dd/MM/yyy"); 
 body.replaceText(yesterdayDate,todayDate) ;
}

【讨论】:

  • 您的代码解决了date-1 毫无意义的问题,因为date 是一个字符串……您也应该提到这一点。
猜你喜欢
  • 2010-11-04
  • 1970-01-01
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-14
相关资源
最近更新 更多