Skip to content

Instantly share code, notes, and snippets.

@davidsword
Last active March 5, 2019 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsword/0578089784417053efa7855aadc103e4 to your computer and use it in GitHub Desktop.
Save davidsword/0578089784417053efa7855aadc103e4 to your computer and use it in GitHub Desktop.
PHP - Fetch and display Google Calendar events as text list and total time
<?php
/**
* Retreive a list events from a Google Calender in PHP.
*
* Useful when using Google Calendar as a project/time log.
* This script can be adapted to peal out events from a specific calendar.
* I use this for my personal timelog'ing. My events follow a naming
* pattern of `{category} - {project}: {details}`.
*
* Uses Google PHP API
* @see https://github.com/google/google-api-php-client
*/
require_once ('/Google/autoload.php');
require_once ('/Google/Service/Calendar.php');
$client = new Google_Client();
$client->setApplicationName( "Client_Library_Examples" );
$client->setDeveloperKey( "YOUR_APP_KEY" );
// Query our Calendar.
$service = new Google_Service_Calendar($client);
$calendar_id = 'username_calendarid@group.calendar.google.com';
$search_term = '#my_project';
$optParams = array(
'maxResults' => 999,
'orderBy' => 'startTime',
'singleEvents' => true,
'q' => $search_term,
'timeMin' => date( 'c', strtotime( "2018-01-01 00:00:01"),
'timeMax' => date( 'c', strtotime( date( 'Y-m-d' )." 23:59:59" ) ),
);
// Get our list of events.
$results = $service->events->listEvents($calendar_id, $optParams);
$sub_total = 0;
$logs = [];
// Cycle events, store duration and log in minutes.
foreach ($results->getItems() as $event) {
$start = strtotime($event->start->dateTime);
$end = strtotime($event->end->dateTime);
$duration = $end - $start;
$sub_total += $duration;
$logs[] = [
'date' => date('Ymd Hi',$start),
'duration' => $duration,
'details' => $event->summary
]
}
// echo "<pre>";
// print_r( $logs, true );
// echo in_hours( $sub_total ) . " HOURS TOTAL";
function in_hours( $minutes ) {
return number_format(round(($minutes/(60*60)),2),2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment