Skip to content

Instantly share code, notes, and snippets.

@bene-we
Last active March 26, 2025 16:59
Show Gist options
  • Save bene-we/e0a306ad6788fec5dbe45cde2de2f140 to your computer and use it in GitHub Desktop.
Save bene-we/e0a306ad6788fec5dbe45cde2de2f140 to your computer and use it in GitHub Desktop.
Calculate the age of a person and write it to the event's description in your birthday calendar using Google Apps Script

Calculate the age of a person and write it to the event's description in your birthday calendar using Google Apps Script

This script uses Google Apps Script to access one's Google Calendar and calculate the age on a person's birthday. In the best case you have a custom calendar where your birthdays are stored at. If not, uncomment line 20 and use the filter function at the bottom.

Steps to setup everything

  1. Head to https://script.google.com/home/my and create a new project. Rename the existing file Code.gs to your liking and paste the code from calculateAge.gs.
  2. Paste your calendar ID in line 9 (you can find it in the Google Calendar Settings)
  3. Make sure to add the birth year of a person to the location field (or customize the script)
  4. Customize the message in line 36
  5. Hit run and see the messages appear in your calendar events for the current year!
  6. Create a trigger to run this every year to calculate the correct age

const CALENDAR_ID = "[email protected]";
const TAG_NAME = 'calculatedAge';
const FORCE_OVERWRITE = false;
// Control for how many years in the future the age should be calculated
// Set to `1` to only cover the current year
const CALCULATE_FOR_YEARS = 2;
// Set to `true` to enable debug logging
const DEBUG = false;
/*
* Calculate the age of birthday people in each year and add a short note in the description
*/
function calculateAge() {
// Get Calendar 'Birthdays'
const birthdayCal = CalendarApp.getCalendarById(CALENDAR_ID);
const yearOfExecution = (new Date()).getFullYear()
for (var i = 0; i < CALCULATE_FOR_YEARS; i++) {
// Select date range of the year that is currently processed
const currentYear = yearOfExecution + i;
const start = new Date(currentYear + '-01-01');
const end = new Date(currentYear + '-12-31');
// Fetch events from Birthday Calendar
var birthdays = birthdayCal.getEvents(start, end);
// Filter Birthdays out of Default Calendar (if no specific Birthday Calendar is present)
// birthdays = birthdays.filter(filterBirthdays);
if (DEBUG) {
Logger.log(`Scanning ${birthdays.length} birthdays in year ${currentYear} ...`)
}
for (var j = 0; j < birthdays.length; j++) {
e = birthdays[j];
// Year of birth is stored in the Location field of the event
const birthYear = e.getLocation()
const birthYearIsNotEmpty = birthYear !== ""
if (birthYearIsNotEmpty) {
const descriptionIsEmpty = e.getDescription() === ""
const tagIsEmpty = isNaN(parseInt(e.getTag(TAG_NAME)))
// Calculate the age if it has not been done before OR `FORCE_OVERWRITE` is true
if ((descriptionIsEmpty && tagIsEmpty) || FORCE_OVERWRITE) {
const calculatedAge = Math.round(currentYear - birthYear);
// Customize the description here
const description = e.getTitle() + ' wird heute ' + calculatedAge + ' Jahre!'
e.setDescription(description);
// Save calculated age in tag
e.setTag(TAG_NAME, calculatedAge);
if (DEBUG) {
const logEntry = {
name: e.getTitle(),
birthyear: e.getLocation(),
currentYear: Math.round(currentYear),
calculatedAge: Math.round(calculatedAge),
}
Logger.log(`${description} \n ${JSON.stringify(logEntry, null, 2)}`)
}
}
}
}
}
}
/*
* Filter the birthdays out of the fetched events
* Add additional filters if you don't have a specific Birthday Calendar
*/
function filterBirthdays(event) {
// Add filter here (e.g. event.getColor === CalendarApp.Color.YELLOW)
return event.isAllDayEvent();
}
@bene-we
Copy link
Author

bene-we commented May 3, 2024

@ruifchaves sorry for getting back to you this late. You really put some effort into this, didn't you! I think I never experienced this issue myself since I've set default reminders on the previous day, and so far I didn't have problems with pop-up reminders. Yet it sounds really buggy what you've experienced, I just don't have an idea what to do about it

@dribnus
Copy link

dribnus commented May 3, 2024

Thank you

@bene-we
Copy link
Author

bene-we commented May 3, 2024

@Beeger just an idea from my side, I've seen that you wrapped the script with myFunction, are you sure that you call that function somewhere? I just tested my version and logs are working correctly, but they only show up if the code actually runs.

Apart from that, I cannot see the full calendar event so I cannot see anything wrong, and second it shouldn't be a big deal but I would try to hide personal details like the calendarId when posting on the internet.

@bene-we
Copy link
Author

bene-we commented May 3, 2024

Thank you

No worries! Let me know if you get it to work! Apart from that, nothing dumb about not being experienced in a topic yet, keep it up 🥳

@jjj120
Copy link

jjj120 commented Jul 25, 2024

I have changed the code a little bit, to write the age into the title, so if the original title is "John Doe Birthday", and John Doe gets 34 years old, it gets changed to "John Doe (34) Birthday". I thought I'd share the new code here, if someone wants to use it.
Also thanks @bene-we for the starting point!

To not paste all the code in the comment, you can find it here.

The README should be the same, except for a few small changes:

  • added a constant for the calendar id, so change it at the top
  • added another constant for the title appendix, so the "Birthday" part of the example (If you dont want any appendix, you can probably just set it to an empty string)

@Beeger
Copy link

Beeger commented Jul 25, 2024

@jjj120 Love this idea but I can't get it to work. I copy and pasted the code directly, and then changed the calendar ID at the top, but now nothing updates. The title doesn't change and it doesn't update the description anymore either. Could there be something missing from the code? Or something else I need to change on my end? Thanks!

@jjj120
Copy link

jjj120 commented Jul 25, 2024

Hm weird. I made some changes to the script to be a little more resilient, for me it works now.
If it still doesn't for you, do you get any error message from the script? Or is it running and just doing nothing?
You should see a log message of the name of each birthday that gets changed.

@Beeger
Copy link

Beeger commented Jul 25, 2024

No error messages, just this:

image

@jjj120
Copy link

jjj120 commented Jul 26, 2024

Which function are you executing? For me it works when executing calcAge5(), but I think not the others, because they need values passed to them.
If it's not that, could you give an example on how the titles of your calendar events look like?

@bene-we
Copy link
Author

bene-we commented Jul 26, 2024

@jjj120 thanks for sharing! Just keep in mind that you have FORCE_OVERWRITE set to true in your Gist, might not be the desired configuration.
I also detected a bug where the calculated age was wrong if being calculated for future years. You solved that very nicely! I just used another for ... loop, will update my Gist shortly

@bene-we
Copy link
Author

bene-we commented Jul 26, 2024

The script has been updated:

  • fixed a bug where the age is calculated incorrectly for future years
  • improved variable naming
  • improved logging output (configurable by the DEBUG variable)
  • small improvements

@trivers27
Copy link

Hi! I would like to preface that I basically have no coding experience and am new to Apps Script, but this post has already helped me so much - so thank you! And also, I appreciate any guidance you can provide and patience.

I have one calendar that I would like to include both birthdays and anniversaries, and was able to add both the calculated age into the titles and descriptions.

But I am having trouble filtering birthdays from anniversary events. I am assuming I have not edited the filter code correctly.

When I try to run "filterBirthdays" as the code is written here, it gives me the error:

TypeError: Cannot read properties of undefined (reading 'isAllDayEvent')
filterBirthdays @ Code.gs:128

I noticed someone in an above comment added code to filter by anniversary as well, but I thought I should tackle one thing at a time.

ANy help is appreciated!

@trivers27
Copy link

Another error I am running into is

"Exceeded maximum execution time"

@dribnus
Copy link

dribnus commented Oct 28, 2024

I've been trying to play around with this script and now have all kinds of confusion. What I'm trying to accomplish may be a blend of the different scripts that are already posted. I love the option to choose how many years to forward on the calculation, but also really want the age to show up in the title instead of description. I can't seem to get both of those to happen at the same time.

@bene-we
Copy link
Author

bene-we commented Mar 26, 2025

@dribnus did you get it to work? Adding it to the title instead of the description should be as easy as

const previousTitle = e.getTitle()
e.setTitle(previousTitle + ' | Turns ' + calculatedAge + ' today!')

Didn't test it so, don't want to mess with my current script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment