Last active
March 5, 2019 21:37
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 = '[email protected]'; | |
$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