我在基于sinatra的应用程序上工作,我从谷歌日历中获取事件并将所有事件显示为列表。但是,当我尝试获取全天活动的开始和结束日期时,我遇到了一个异常错误。
由于全天事件的对象类型为Date,而定时事件的对象类型为dateTime,因此不会显示这两个对象,我得到的错误是:
没有名为dateTime的方法
当只有定时事件(dateTime对象)事件时它可以正常工作,但是当有一整天事件(日期对象)时没有。
任何帮助都会很棒。
代码:
require 'rubygems'
require 'google/api_client'
require 'date'
# modified from 1m
# Update these to match your own apps credentials
service_account_email = "" # Email of service account
key_file = "" # File containing your private key
key_secret = 'notasecret' # Password to unlock private key
# Get the Google API client
client = Google::APIClient.new(:application_name => 'GCalendar',
:application_version => '1.0.0')
# Load your credentials for the service account
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/calendar',
:issuer => service_account_email,
:signing_key => key)
motd = Array.new
summary = ""
description = ""
tickerEvent = " "
# Start the scheduler
# Request a token for our service account
client.authorization.fetch_access_token!
# Get the calendar API
calendar = client.discovered_api('calendar','v3')
today = DateTime.now().to_s
# Execute the query
result = client.execute(:api_method => calendar.events.list,
:parameters => {'calendarId' => 'idNo',
'timeMin' => today,
'singleEvents' => true,
'orderBy' => 'startTime'})
events = result.data.items
events.each do |e|
if(DateTime.now() >= e.start.dateTime)
summary = e.summary
description = e.description
tickerEvent = summary.to_s + " - " +description.to_s
motd.push(tickerEvent)
elsif(DateTime.now() >= e.end.dateTime)
motd.delete(e)
end
end
motd.clear
end
有没有办法检查事件是Date类型还是DateTime类型?
在google api中,start dateTime和end dateTime看起来像(这是一个定时事件):
"start": {
"dateTime": "2013-12-03T12:30:00+13:00",
"timeZone": "Pacific/Auckland"
},
"end": {
"dateTime": "2013-12-03T13:00:00+13:00",
"timeZone": "Pacific/Auckland"
},
而全日活动如下:
"start": {
"date": "2014-01-17"
},
"end": {
"date": "2014-01-18"
},
它们的类型不同,这就是造成错误的原因。
干杯
答案 0 :(得分:0)
该方法为event.start.date_time
而非event.start.dateTime
。
对于没有时间关联的事件,event.start.date_time
将返回nil。然后,您可以拨打event.start.date
,这应该只返回日期。