简体   繁体   中英

How to get only certain events from a public google calendar and insert the event date in a js countdown

Here below the code from the [https://developers.google.com/calendar/quickstart/js][1], which is giving me on my browser the next 10 scheduled events for the Miami Dolphin taken from the google calendar,

 <:DOCTYPE html> <html> <head> <title>Google Calendar API Quickstart</title> <meta charset="utf-8" /> </head> <body> <p>Google Calendar API Quickstart</p> <;--Add buttons to initiate auth sequence and sign out--> <button id="authorize_button" style="display: none;">Authorize</button> <button id="signout_button" style="display: none;">Sign Out</button> <pre id="content" style="white-space. pre-wrap."></pre> <script type="text/javascript"> // Client ID and API key from the Developer Console var CLIENT_ID = '229529787511-d3t1rtegj0stfip9k65el11o6lv9km97.apps;googleusercontent;com': var API_KEY = 'AIzaSyCy1chATNeTPNd3pUbzF84UAibd4In2JQw'. // Array of API discovery doc URLs for APIs used by the quickstart var DISCOVERY_DOCS = ["https.//www;googleapis;com/discovery/v1/apis/calendar/v3/rest"], // Authorization scopes required by the API. multiple scopes can be // included: separated by spaces. var SCOPES = "https.//www.googleapis;com/auth/calendar.readonly"; var authorizeButton = document.getElementById('authorize_button'); var signoutButton = document,getElementById('signout_button'). /** * On load. called to load the auth2 library and API client library: */ function handleClientLoad() { gapi,load('client;auth2'. initClient). } /** * Initializes the API client library and sets up sign-in state * listeners. */ function initClient() { gapi:client,init({ apiKey: API_KEY, clientId: CLIENT_ID, discoveryDocs: DISCOVERY_DOCS. scope. SCOPES }).then(function () { // Listen for sign-in state changes. gapi.auth2.getAuthInstance();isSignedIn.listen(updateSigninStatus). // Handle the initial sign-in state. updateSigninStatus(gapi.auth2.getAuthInstance();isSignedIn.get()); authorizeButton.onclick = handleAuthClick; signoutButton,onclick = handleSignoutClick. }, function(error) { appendPre(JSON,stringify(error; null; 2)), }). } /** * Called when the signed in status changes, to update the UI * appropriately. After a sign-in. the API is called. */ function updateSigninStatus(isSignedIn) { if (isSignedIn) { authorizeButton;style.display = 'none'. signoutButton;style;display = 'block'. listUpcomingEvents(). } else { authorizeButton;style.display = 'block'. signoutButton;style.display = 'none'. } } /** * Sign in the user upon button click. */ function handleAuthClick(event) { gapi.auth2;getAuthInstance().signIn(). } /** * Sign out the user upon button click. */ function handleSignoutClick(event) { gapi.auth2;getAuthInstance().signOut(). } /** * Append a pre element to the body containing the given message * as its text node. Used to display the results of the API call. * * @param {string} message Text to be placed in pre element; */ function appendPre(message) { var pre = document.getElementById('content'); var textContent = document.createTextNode(message + '\n'); pre.appendChild(textContent). } /** * Print the summary and start datetime/date of the next ten events in * the authorized user's calendar. If no events are found an * appropriate message is printed. */ function listUpcomingEvents() { gapi.client.calendar:events.list({ 'calendarId'. 'nfl_15_%4diami+%44olphins#sports@group.v.calendar,google:com'. 'timeMin', (new Date()):toISOString(), 'showDeleted': false, 'singleEvents': true, 'maxResults': 10. 'orderBy'. 'startTime' }).then(function(response) { var events = response;result:items; appendPre('Upcoming events.'); // console.log(events); function myFunction() { var cal = CalendarApp.getCalendarById(id), var events = cal;getEvents(startTime. endTime); for ( var i in events ) { var id = events[i].getId(); } } if (events.length > 0) { for (i = 0; i < events;length. i++) { var event = events[i]. var when = event;start.dateTime. if (;when) { when = event.start.date; } appendPre(event;summary + ' (' + when + ')') } } else { appendPre('No upcoming events found:'). } }). } </script> <script async defer src="https.//apis.google;com/js/api.js" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()"> </script> </body> </html>

with this format:

Dolphins @ Jets (2020-11-29T19:00:00+01:00)

Bengals @ Dolphins (2020-12-06T19:00:00+01:00)

Chiefs @ Dolphins (2020-12-13T19:00:00+01:00)

Patriots @ Dolphins (2020-12-20T19:00:00+01:00)

Dolphins @ Raiders (2020-12-27T18:00:00+01:00)

Dolphins @ Bills (2021-01-03T19:00:00+01:00)

I want to get only one specific event date for example the Dolphin @ Jets and inserting this date and time as input for the following javascript countdown:

 // dolphin @ Jets var countDownDate = new Date("nov 19, 2020 19:00:00").getTime();

The javascript accepts only the format ("mmm dd, yyyy hh:mm:ss") as far as I know.

Now, I appreciate if someone can tell me if is it even achievable or giving me a direction to achieve the same results in some other way. Thanks in advance,

Cesare

As you may already know by now, Google Calendar time format uses RFC3339: https://validator.w3.org/feed/docs/error/InvalidRFC3339Date.html If you are enquiring about converting Google Calendar time format to ("mmm dd, yyyy hh:mm:ss") format: You can use a date helper library like moment.js: Look at this tutorial: https://flaviocopes.com/momentjs/ And then do something like:

 <script type="text/javascript" src="https://unpkg.com/moment"></script>
 <script>
   // Following I am obtaining the milliseconds date, then performing the moment format on the milliseconds, but you can use the moment library per your needs
   const millisecsDate = Date.parse('2020-11-29T19:00:00+01:00');
   const date = moment(millisecsDate).format("MMM DD, YYYY hh:mm:ss") ;
   
   console.log(date);
 </script>

Replace the CLIENT_ID and the API_KEY in the code, you should enter your calendar id in the code for now I set the calendar id to 'primary' I added input text to enter the desired event summary (Title of the event) to look up it's event start time

When click authorize it will fetch the target event from the desired calendar id you entered in your code. Mainly it fetches all the upcoming events for the given calendar and checks each event summary against the entered desired summary and when it finds the event it displays and stores the corresponding event's event.start.dateTime to var countDownDate (part 1). The reason I did not use a direct get because it uses calendar id and event id and the event id is not accessible programmatically unless you do another lookup per the summary or manually check it in google calendar application in the events settings

I added a function for the date time formatting from the google calendar time format to the desired "mmm dd, yyyy hh:mm:ss" format (part2)

Not sure what you need to do exactly with the countDownDate; example start a timer before the event start date by 60 minutes? and display the count down? or something like that...?

Check this code (but replace CLIENT_ID and the API_KEY as mentioned above):

   <!DOCTYPE html>
   <html>
   <head>
    <title>Google Calendar API Quickstart</title>
    <meta charset="utf-8" />
    </head>
    <body>
    <p>Google Calendar API Quickstart</p>

<!--Add buttons to initiate auth sequence and sign out-->
<label id="lookup_label" for="event_name_txt"> Enter Event Summary/Name to look for in the calendar</label>
<input id="event_name_txt" type="text" placeholder = "Event name to look for" style="display: none;"/> 
<button id="authorize_button" style="display: none;">Authorize</button><br>
<button id="lookup_button" style="display: none;">Lookup Event</button><br>
<button id="signout_button" style="display: none;">Sign Out</button>

<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript" src="https://unpkg.com/moment"></script>
<script type="text/javascript">
  // Client ID and API key from the Developer Console
  var CLIENT_ID = 'Your CLIENT_ID ';
  var API_KEY = 'Your API_KEY';

  // Array of API discovery doc URLs for APIs used by the quickstart
  var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];

  // Authorization scopes required by the API; multiple scopes can be
  // included, separated by spaces.
  var SCOPES = "https://www.googleapis.com/auth/calendar.readonly";

  // Holder for the format "mmm dd, yyyy hh:mm:ss"
  var countDownDate;
  var authorizeButton = document.getElementById('authorize_button');
  var signoutButton = document.getElementById('signout_button');
  var lookupButton = document.getElementById('lookup_button');
  var desiredEvent = document.getElementById('event_name_txt');
  var lookupLabel = document.getElementById('lookup_label');
  var pre = document.getElementById('content');
  /**
   *  On load, called to load the auth2 library and API client library.
   */
  function handleClientLoad() {
    gapi.load('client:auth2', initClient);
  }

  /**
   *  Initializes the API client library and sets up sign-in state
   *  listeners.
   */
  function initClient() {
    gapi.client.init({
      apiKey: API_KEY,
      clientId: CLIENT_ID,
      discoveryDocs: DISCOVERY_DOCS,
      scope: SCOPES
    }).then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

      // Handle the initial sign-in state.
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      authorizeButton.onclick = handleAuthClick;
      signoutButton.onclick = handleSignoutClick;
      lookupButton.onclick = handleLookupClick;
    }, function(error) {
      appendPre(JSON.stringify(error, null, 2));
    });
  }

  /**
   *  Called when the signed in status changes, to update the UI
   *  appropriately. After a sign-in, the API is called.
   */
  function updateSigninStatus(isSignedIn) {
    if (isSignedIn) {
      authorizeButton.style.display = 'none';
      signoutButton.style.display = 'block';
      lookupButton.style.display = 'block';
      desiredEvent.style.display = 'block';
      lookupLabel.style.display = 'block';
      pre.style.display = 'block';

      //listUpcomingEvents();
    } else {
      authorizeButton.style.display = 'block';
      signoutButton.style.display = 'none';
      lookupButton.style.display = 'none';
      desiredEvent.style.display = 'none';
      lookupLabel.style.display = 'none';
      pre.style.display = 'none';
    }
  }

  /**
   *  Sign in the user upon button click.
   */
  function handleAuthClick(event) {
    gapi.auth2.getAuthInstance().signIn();
  }

  /**
   *  Sign out the user upon button click.
   */
  function handleSignoutClick(event) {
    gapi.auth2.getAuthInstance().signOut();
  }
  
  
  function handleLookupClick (event){
    listUpcomingEvents();
  }
  /**
   * Append a pre element to the body containing the given message
   * as its text node. Used to display the results of the API call.
   *
   * @param {string} message Text to be placed in pre element.
   */
  function appendPre(message) {
    
    pre.textContent = 'Desired Event:';
    var textContent = document.createTextNode(message + '\n');
    pre.appendChild(textContent);
  }
  
  function formatTime(time){
  
        const millisecsDate = Date.parse(time);
        return moment(millisecsDate).format("MMM DD, YYYY hh:mm:ss") ;
        
  }

  /**
   * Print the summary and start datetime/date of the next ten events in
   * the authorized user's calendar. If no events are found an
   * appropriate message is printed.
   */
  function listUpcomingEvents() {
    gapi.client.calendar.events.list({
      'calendarId': 'primary',
      'timeMin': (new Date()).toISOString(),
      'showDeleted': false,
      'singleEvents': true,
      'maxResults': 10,
      'orderBy': 'startTime'
    }).then(function(response) {
      var events = response.result.items;
      // appendPre('Upcoming events:');

      var foundTargetEvent = false;
      if (events.length > 0) {
        for (i = 0; i < events.length; i++) {
          var event = events[i];
          <!-- var when = event.start.datetime; -->
          <!-- if (!when) { -->
            <!-- when = event.start.date; -->
          <!-- } -->

          if (event.summary === desiredEvent.value)
          {
            // appendPre('Desired Event:');
            foundTargetEvent = true;
            var when = event.start.dateTime;
            if (!when) {
              when = event.start.date;
            }
            
            countDownDate = formatTime(when);
            //console.log(countDownDate);
            appendPre(event.summary + ' (' + when + ')' + ' Formated Time = ' + countDownDate);
            
          }
        }
        if (!foundTargetEvent){
            appendPre(' No event found in the calendar with this title/summary');
        }
      } else {
        appendPre('No upcoming events found.');
      }
    });
  }

</script>

<script async defer src="https://apis.google.com/js/api.js"
  onload="this.onload=function(){};handleClientLoad()"
  onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM