Android平台下如何从Google Calendar获取当日所有事件
Got it, let's break this down for you. You want to pull all today’s events from every calendar linked to a user’s Google account, grabbing title, description, and time details—without having to hardcode or ask for calendar IDs or event IDs. Here’s a step-by-step implementation using the Google Calendar API:
Prerequisites
First, make sure your app is set up with OAuth2 authentication and has the https://www.googleapis.com/auth/calendar.readonly scope. This lets you safely read the user’s calendar data without making changes.
Step 1: Fetch All User Calendars
You don’t need to specify calendar IDs manually—instead, use the calendarList.list() endpoint to get every calendar the user has access to (including their primary calendar, shared calendars, etc.).
Example Code (Python)
from googleapiclient.discovery import build from datetime import datetime, timedelta # Assume you already have an authenticated 'service' object (from OAuth2 flow) service = build('calendar', 'v3', credentials=credentials) # Get all calendars in the user's account calendar_list_response = service.calendarList().list().execute() user_calendars = calendar_list_response.get('items', [])
Step 2: Query Today’s Events for Each Calendar
Loop through each calendar from the list above, and use events.list() to fetch events that fall within today’s time window. The key here is setting the correct timeMin and timeMax to target only today’s events.
Key Parameters for events.list()
timeMin: Start of today (in ISO 8601 format, e.g.,2024-05-20T00:00:00Z)timeMax: Start of tomorrow (to capture all events ending before midnight today)singleEvents=True: Expands recurring events into individual daily instances (so you don’t miss repeated events today)orderBy='startTime': Sorts events chronologically
Full Event Fetch Code
# Set today's time range (UTC; adjust timezone if needed) today_utc_start = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0).isoformat() + 'Z' today_utc_end = (datetime.utcnow() + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0).isoformat() + 'Z' all_today_events = [] for calendar in user_calendars: calendar_id = calendar['id'] # Fetch events for today in this calendar events_response = service.events().list( calendarId=calendar_id, timeMin=today_utc_start, timeMax=today_utc_end, singleEvents=True, orderBy='startTime' ).execute() calendar_events = events_response.get('items', []) # Extract required fields for each event for event in calendar_events: event_details = { 'title': event.get('summary', 'No Title'), # Fallback if no title exists 'desc': event.get('description', 'No Description'), # Fallback for empty descriptions 'time': {} } # Handle both timed events and all-day events if 'dateTime' in event['start']: event_details['time']['start'] = event['start']['dateTime'] event_details['time']['end'] = event['end']['dateTime'] else: # All-day events use 'date' instead of 'dateTime' event_details['time']['start'] = event['start']['date'] event_details['time']['end'] = event['end']['date'] all_today_events.append(event_details)
Important Notes
- Time Zones: If you want to use the user’s local time instead of UTC, add the
timeZoneparameter toevents.list()(e.g.,timeZone='America/New_York') and adjusttoday_utc_start/today_utc_endto local time ISO strings. - Pagination: If a user has a lot of events,
events.list()might return results in pages. Check fornextPageTokenin the response and loop until all pages are fetched. - Filtering Calendars: If you want to exclude certain calendars (like the default "Birthdays" calendar), add a check when iterating
user_calendars(e.g., skip ifcalendar['summary'] == 'Birthdays').
Final Output
The all_today_events list will contain every event from every user calendar today, each with the title, desc, and time fields you need—no manual calendar or event IDs required.
内容的提问来源于stack exchange,提问作者Luke C

