Flutter Google Calendar API V3 incorrectly importing datetimes

I’m currently using Google Calendar API to get an event list from a service account for a Flutter app I’m developing. The issue is that, although the timezone is correct, the datetime value from “start” and “end” is automatically set from the original timezone to always UTC-0. But for some reason, “updated” keeps the original timezone.

For example, this is how it looks from the Google OAuth2 example site:

...
"updated": "2023-11-28T16:36:50.547Z",
...
"start": {
"dateTime": "2022-08-31T17:00:00-05:00",
"timeZone": "America/Mexico_City"
},
...

But the dateTime of start and end prints like this:

print(event.start!.dateTime!);
print(event.updated!);

2022-08-31 22:00:00.000Z
2023-11-28 16:36:50.547Z

Here’s the code:

import 'package:googleapis/calendar/v3.dart' as calendar;
...
final clientAccess = await clientViaServiceAccount(_credentials, [calendar.CalendarApi.calendarScope]);
final calendars = calendar.CalendarApi(clientAccess);

final startOfDay = DateTime(selectedDay.year, selectedDay.month, selectedDay.day, 0, 0, 0).toUtc();
final endOfDay = DateTime(selectedDay.year, selectedDay.month, selectedDay.day+1, 7, 59, 59);

calendar.Events access = await calendars.events.list(mapEvents, timeMin: startOfDay.toUtc(), timeMax: endOfDay.toUtc(), timeZone: "America/Mexico_City");
    
var eventMap = Map<DateTime, List<calendar.Event>>();
    
for (final event in access.items!) {
   if (event.start == null || event.start!.dateTime == null) {
      continue;
   }

   print(event.start!.dateTime!);
   print(event.updated!);

   final start = event.start!.dateTime!.add(Duration(hours: -6));

   var dateKey = DateTime(start.year, start.month, start.day);
   if (event.recurrence != null) {
      dateKey = DateTime(selectedDay.year, selectedDay.month, selectedDay.day);
   }
   if (eventMap.containsKey(dateKey)) {
      eventMap[dateKey]!.add(event);
   } else {
      eventMap[dateKey] = [event];
   }
}
...

My initial approach was setting the variable start like this:
final start = event.start!.dateTime!.add(Duration(hours: -6));
But later on I found several events from the calendar that had the timezone UTC-5 alongside UTC-6.

Any help is appreciated.

Leave a Comment