设置小时不工作

时间:2012-11-21 15:45:52

标签: javascript google-apps-script google-calendar-api

有没有人知道为什么这个简单的代码不起作用?:

var formattedSched = new Date(sched).setHours(15);

我只是想通过应用脚本为Google日历中的日历活动添加时间。我甚至在w3页面上使用基本相同的样本设定时间。 http://www.w3schools.com/jsref/jsref_sethours.asp

但每次我运行脚本在Google日历中创建一个事件时,我都会收到一条错误消息,谷歌认为这是一个数字,而不是日期对象。它没有setHours()工作正常,但有了它,谷歌认为这是一个数字。感谢

更新:好的,我拆分了一个测试函数来尝试记录发生的事情:

function testsetcal() {

  var formattedSched = new Date(); Logger.log(formattedSched.setHours(15))

  CalendarApp.getDefaultCalendar()
  .createEvent('Commo', formattedSched, formattedSched);
}

且没有 setHours的记录器结果为:Wed Nov 21 08:12:33 PST 2012

记录器结果 with setHours是:1.35352881266E12,它看起来与w3页面上的示例结果完全不同。

更新:仍然无法正常工作,并且setHours与主变量分开时得到相同的记录器结果:1.35352881266E12

function testsetcal() {

  var formattedSched = new Date(); 
  var withHours = formattedSched.setHours(15);

  Logger.log(withHours);

  CalendarApp.getDefaultCalendar()
  .createEvent('Commo', withHours, withHours);
}

更新:好的哇 - 这很奇怪。我去了我的谷歌日历删除所有测试事件,至少只是我认为成功的那些。然后我发现有一些比我想象的要多,有些被设置为1500 - 然后我回到代码并发现setHours()在谷歌日历创建事件的外部工作如下:

function testsetcal() {  
  var formattedSched = new Date(); 

  formattedSched.setHours(15);

  Logger.log(formattedSched.setHours(15));

  CalendarApp.getDefaultCalendar()
  .createEvent('Commo', formattedSched, formattedSched);
}

因此,此代码将小时设置为1500,但该部分代码不会包含在事件的创建中。完全让我感到惊讶,但这似乎是解决方案。

3 个答案:

答案 0 :(得分:0)

不完全是,您当前正在返回对var的setHours响应,请尝试

var formattedSched = new Date(sched);
formattedSched.setHours(15);

答案 1 :(得分:0)

您需要将其与您引用的示例分开。

var formattedSched = new Date(sched);
formattedSched.setHours(15);

您正在尝试在尚未创建的日期对象上实现setHours()

答案 2 :(得分:0)

猜猜我应该继续关闭它。谢谢你的回复。这段代码对我有用,可以用时间将事件输入GCal:

function testsetcal() {  
  var formattedSched = new Date(); 

  formattedSched.setHours(15);

  Logger.log(formattedSched.setHours(15));

  CalendarApp.getDefaultCalendar()
  .createEvent('Commo', formattedSched, formattedSched);
}

.setHours必须在.createEvent之外。