So Google Calendar is pretty picky when it comes to working with its API. We have an application that will fetch the calendar events for a 2 month timeframe. It will soon be changed to allow for a different start and end time. So first of all lets look at what the URL must be formatted as:
https://www.googleapis.com/calendar/v3/calendars/test%40gmail.com/events?key=<your-api-key-goes-here>&timeMin=2014-06-11T12:00:00Z&timeMax=2014-08-12T12:00:00Z&orderBy=starttime&singleEvents=true
So notice that the timMin is the calendars start time and is formatted as such:
2014-06-11T12:00:00Z
This was a pain in the ass to convert correctly. I never was able to completely get the format correctly using Ruby strftime but I got really close:
Date.today.strftime("%Y-%m-%dT%l:%M:%S") == 2014-06-11T12:00:00
So I cheated and did:
Date.today.strftime("%Y-%m-%dT%l:%M:%S") + "Z"
Now for the fun part. I just refactored older code. I just want to show the before and after for the fun of it!!!
BEFORE:
[sourcecode language="ruby"]
def current_calendar
@cal = nil
@api_key = 'zzzzzzzz'
@cc_today = Time.now
@cc_yr = @cc_today.year
@cc_mth = @cc_today.month
# We want to get two mths of events
# so create a Time for next month
if @cc_mth == 12
@cc_mth = 1
@cc_yr += 1
else
@cc_mth += 1
end
@cc_next_mth = Time.new(@cc_yr, @cc_mth, 1)
@days_in_month = Time.days_in_month(@cc_mth)
@min_date = '%Y-%m-01'
@max_date = '%Y-%m-'
@max_date = @max_date + @days_in_month.to_s
@timeMin = @cc_today.strftime(@min_date)
@timeMax = @cc_next_mth.strftime(@max_date)
@timeMin = @timeMin + 'T00:00:01Z'
@timeMax = @timeMax + 'T23:59:59Z'
@myString = '?'
@myString = @myString + 'key='
@myString = @myString + @api_key
@myString = @myString + '&'
@myString = @myString + 'timeMin='
@myString = @myString + @timeMin
@myString = @myString + '&'
@myString = @myString + 'timeMax='
@myString = @myString + @timeMax
@myString = @myString + '&'
@myString = @myString + 'orderBy=starttime'
@myString = @myString + '&'
@myString = @myString + 'singleEvents=true'
@email = self.url.gsub(/@/ , '%40')
@url_params = 'https://www.googleapis.com/calendar/v3/calendars/'
@url_params = @url_params + @email
@url_params = @url_params + '/events'
@url_params = @url_params + @myString
@response = HTTParty.get(@url_params)
@cal = @response.parsed_response['items']
end
[/sourcecode]
AND AFTER:
[sourcecode language="ruby"]
def current_calendar
api_key = 'zzzzzzzzz'
time_min = Date.today.strftime("%Y-%m-%dT%l:%M:%S") + "Z"
time_max = (Date.today + 2.months + 1.day).strftime("%Y-%m-%dT%l:%M:%S") + "Z"
url = "https://www.googleapis.com/calendar/v3/calendars/#{self.url.gsub(/@/ , '%40')}/events?key=" +
api_key + "&timeMin=" + time_min + "&timeMax=" + time_max + "&orderBy=starttime&singleEvents=true"
response = HTTParty.get(url)
@cal = response.parsed_response['items']
end
[/sourcecode]
Moral of the story ....
Ruby is a fantastic language with methods for just about everything. Why do things the hard way???