0

I have a nice function that shows all events on my calendar for this month but I can't figure out how to change that to this week (monday to sunday).

I can change the list by changing date to today's date and adding days for example. I tried some things with Utilities.formatDate but this gives me weeknumbers, no dates. I have no clue how to get the current week.

function listEvents2() {
  var date = new Date();
  var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
  var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
  var events2 = CalendarApp.getDefaultCalendar().getEvents(firstDay, lastDay);

  var data2 = [];
  data2.push("Deze maand: ");
  if (events2 && events2.length > 0) {
    for (i = 0; i < events2.length; i++) {
      data2.push(events2[i].getTitle()+' : '+Utilities.formatDate(events2[i].getStartTime(),Session.getScriptTimeZone(),"dd MMMM HH:mm")+' - '+Utilities.formatDate(events2[i].getEndTime(),Session.getScriptTimeZone(),"HH:mm"))
    }
    return data2;
  }
  else {
    return ['No events found','',''];
  }
}

I would like some tips how to achieve this.

Edit: Maybe I need to explain more. This function is used for a personal weekplanner dashboard with HtmlService. There is another function that gives a list of today's events.

Edit 2: Here is my working code:

function email() {


  var date = new Date();
  var day = date.getDay();
  var firstDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()-day+1);
  var lastDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()-day+8);
  var events2 = CalendarApp.getCalendarById(CalendarID).getEvents(firstDay, lastDay);

  var data2 = [];
  data2.push("<b>Title</b>");
  if (events2 && events2.length > 0) {
    for (i = 0; i < events2.length; i++) {
      data2.push(Utilities.formatDate(events2[i].getStartTime(),Session.getScriptTimeZone(),"EEEE dd/MM")+ ' ' + Utilities.formatDate(events2[i].getStartTime(),Session.getScriptTimeZone(),"HH:mm") +'<br/>'+events2[i].getTitle())
    }

    return data2;
  } else {
    return ['Nothing to do'];
  }
}

I decided to split the lists per calendar to have it more organized. But both answers below work.

There are still two things I need to figure out. First one is how I can get

Session.getScriptTimeZone(),"EEEE dd/MM")

to show EEEE in my native language instead of English.

The other one is that the function gives a perfect list of things to do but it skips empty days. I would like to display the empty days as the dashboard should function like a calendar view planner.

Thanks for the help so far!

3 Answers3

1

Default Calendar Events for one week

function listEvents2() {
  var date = new Date();
  var day= date.getDay();
  var firstDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()-day);
  var lastDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()-day+6);
  var events2 = CalendarApp.getDefaultCalendar().getEvents(firstDay, lastDay);

  var data2 = [];
  data2.push("Deze maand: ");
  if (events2 && events2.length > 0) {
    for (i = 0; i < events2.length; i++) {
      data2.push(events2[i].getTitle()+' : '+Utilities.formatDate(events2[i].getStartTime(),Session.getScriptTimeZone(),"dd MMMM HH:mm")+' - '+Utilities.formatDate(events2[i].getEndTime(),Session.getScriptTimeZone(),"HH:mm"))
    }

    return data2;
  }
  else {
    return ['No events found','',''];
  }
}

All Calendar Events for month or a week

It defaults to a week with null parameter. This is currently setup with an example dialog to display your events but with a few minor modifications identified by comments you can begin using it in your code immediately.

function listEventsForAllCalendars(month) {
  var month=month||false;//defaults to one week
  var date = new Date();
  var day= date.getDay();
  if(month) {
    var firstDay = new Date(date.getFullYear(), date.getMonth(),1 );//These are for one month
    var lastDay = new Date(date.getFullYear(), date.getMonth()+1,0 );
  }else{
    var firstDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()-day);//These are for one week
    var lastDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()-day+6);
  }
  var cals= CalendarApp.getAllCalendars();
  allEvsA=[];//array of objects to store event information
  cals.forEach(function(cal){
    var events=cal.getEvents(firstDay,lastDay);
    events.forEach(function(ev){
      allEvsA.push({calendar:cal.getName(),title:ev.getTitle() ,starttime:Utilities.formatDate(ev.getStartTime(),Session.getScriptTimeZone(), "dd MMMM HH:mm") ,endtime: Utilities.formatDate(ev.getEndTime(),Session.getScriptTimeZone(),"HH:mm")});
    })
  })
  var data2 = [];
  data2.push("Deze maand: ");
  if (allEvsA && allEvsA.length > 0) {
    allEvsA.forEach(function(ev){
      //data2.push(ev.title +' : '+ ev.starttime +' - ' + ev.endtime);//This works with your current scripts
      data2.push(Utilities.formatString('Calendar: %s Event Title: %s Start Time: %s End Time: %s',ev.calendar,ev.title,ev.starttime,ev.endtime));//this is also contains calendar name
    })

    //return data2;//This is for your current script
    var userInterface=HtmlService.createHtmlOutput(data2.join('<br />')).setWidth(1000);//These lines will display your events in a dialog
    SpreadsheetApp.getUi().showModelessDialog(userInterface, "Events for all Calendars"); 
  }
  else {
    //return ['No events found','',''];
    var userInterface=HtmlService.createHtmlOutput('No Events Found').setWidth(1000);//These lines will display your events in a dialog
    SpreadsheetApp.getUi().showModelessDialog(userInterface, "Events for all Calendars"); 
  }
}
Cooper
  • 59,616
  • 6
  • 23
  • 54
  • This works perfect! I have one other problem with the script. When using .getDefaultCalendar it works (with the default calendar offcourse) but as soon as I change .getDefaultCalendar to .getAllCalendars nothing happens... – Nina Bakker Oct 09 '19 at 18:26
  • @NinaBakker Hello Nina! You may be interested in checking out my answer, which shows you how to get the firstday and lastday in another manner as well as using getAllCalendars. Cheers – carlesgg97 Oct 10 '19 at 11:08
  • getDefaultCalendar() returns a calendar. getAllCalendars() returns an array of calendars which requires you to iterate through each one. I’ll give you an example later when I’m not on mobile. – Cooper Oct 10 '19 at 12:40
1

In order to get the dates of the start and the end of the week, you can use the following, modified code:

function listEvents2() {
  var date = new Date();
  var firstDay = new Date();
  var lastDay = new Date();
  firstDay.setDate(firstDay.getDate() - firstDay.getDay() + 1);
  firstDay.setHours(0,0,0,0);
  lastDay.setDate(lastDay.getDate() - lastDay.getDay() + 8);
  lastDay.setHours(0,0,0,0);
  var events2 = CalendarApp.getDefaultCalendar().getEvents(firstDay, lastDay);

  var data2 = [];
  data2.push("Deze maand: ");
  if (events2 && events2.length > 0) {
    for (i = 0; i < events2.length; i++) {
      data2.push(events2[i].getTitle()+' : '+Utilities.formatDate(events2[i].getStartTime(),Session.getScriptTimeZone(),"dd MMMM HH:mm")+' - '+Utilities.formatDate(events2[i].getEndTime(),Session.getScriptTimeZone(),"HH:mm"))
    }
    return data2;
  }
  else {
    return ['No events found','',''];
  }
}

Bear in mind that these dates will take into consideration the timezone that you are in. If you want to work with dates in an easier way, I recommend you check out the library momentjs.

Also, if you want to use getAllCalendars(), you have to take into consideration that the return value of that function is an array of calendars rather than a calendar object (see the documentation). In order to list the events on each calendar, you can again modify the code in the following manner (both modifications):

function listEvents2() {
  var date = new Date();
  var firstDay = new Date();
  var lastDay = new Date();
  firstDay.setDate(firstDay.getDate() - firstDay.getDay() + 1);
  firstDay.setHours(0,0,0,0);
  lastDay.setDate(lastDay.getDate() - lastDay.getDay() + 8);
  lastDay.setHours(0,0,0,0);
  var events2 = [];
  var allCalendars = CalendarApp.getAllCalendars();
  for (var i=0; i<allCalendars.length; i++) {
    var calendarEvents = allCalendars[i].getEvents(firstDay, lastDay);
    events2 = events2.concat(events2, calendarEvents);
  }

  var data2 = [];
  data2.push("Deze maand: ");
  if (events2 && events2.length > 0) {
    for (i = 0; i < events2.length; i++) {
      data2.push(events2[i].getTitle()+' : '+Utilities.formatDate(events2[i].getStartTime(),Session.getScriptTimeZone(),"dd MMMM HH:mm")+' - '+Utilities.formatDate(events2[i].getEndTime(),Session.getScriptTimeZone(),"HH:mm"))
    }
    return data2;
  }
  else {
    return ['No events found','',''];
  }
}
carlesgg97
  • 4,184
  • 1
  • 8
  • 24
  • Sorry I didn't check your whole answer before. Thanks for your help! I will try it out. – Nina Bakker Oct 10 '19 at 17:22
  • It works but my default calendar events come up multiple times (8x). My other calendars (that are shared) shows right. Any idea how to fix that? – Nina Bakker Oct 10 '19 at 18:25
0

You may find this related question useful. It helps you get the Monday (which can be changed to Sunday if you want your weeks to run Sunday-Saturday).

You can use that as your firstDay and then your lastDay is 6 days later than that, so something like:

var lastDay = new Date(firstDay.setDate(firstDay.getDate() + 6))

Be aware that in Javascript the .getDay() method returns 0 if it is a Sunday and 1 if it is Monday [0]. Likewise with months, January is 0, February is 1 etc. [1]

[0] https://www.w3schools.com/jsref/jsref_getday.asp

[1] https://www.w3schools.com/jsref/jsref_getmonth.asp

rsomji
  • 140
  • 7