Aniversários no Google Agenda com idade

Por muitos anos eu uso o calendário do Google. Sempre foi incompreensível o motivo pelo qual não exibe a idade das pessoas dos Contatos do Google no momento do nascimento, aniversário ou outros eventos significativos.



Quando comecei a procurar propositadamente a resposta para essa pergunta, descobri que a solicitação para exibir a idade no calendário do Google é bastante popular e ainda não há uma resposta definitiva para ela. Isso me incentivou a criar uma solução baseada no Google Apps Script.


Por que scripts do google?


Não queria usar nenhuma plataforma ou serviço de terceiros, porque todos os meus contatos estão no catálogo de endereços do Google. Eu também não queria usar um aplicativo ou complemento que coletasse meus dados pessoais para fins incompreensíveis. Era necessária uma estrutura de trabalho transparente.


Onde está o código?


Não posso dizer que o roteiro foi escrito do zero - aproveitei os desenvolvimentos de Bryan Patterson , que foram publicados há 6 anos, em 2014.


Aqui está o resultado:


Aniversários e datas especiais para o seu calendário.gs
//   var contactsCal; var defaultCal; var now; var fromDate; var toDate; var events; //  (function() { contactsCal = CalendarApp.getCalendarById('addressbook#contacts@group.v.calendar.google.com'); defaultCal = CalendarApp.getDefaultCalendar(); //       // var defaultCal = CalendarApp.getCalendarById('regrncqXXXXXXp07eihepag74@group.calendar.google.com'); //   now = new Date(); fromDate = new Date(now.getTime()); toDate = new Date(now.getTime() + 31 * (1000 * 60 * 60 * 24)); // + 31     Logger.log(' : ' + Utilities.formatDate(fromDate, 'Asia/Yekaterinburg', 'MMMM dd, yyyy HH:mm:ss Z')); Logger.log(' : ' + Utilities.formatDate(toDate, 'Asia/Yekaterinburg', 'MMMM dd, yyyy HH:mm:ss Z')); events = contactsCal.getEvents(fromDate, toDate); Logger.log(' : ' + events.length); })(); function birthdayAgeToCalendar() { //  for (var i in events) { Logger.log('birthdayAgeToCalendar.  . : ' + events[i].getTitle()); var name = events[i].getTitle().split(" –  ")[0]; var contacts = ContactsApp.getContactsByName(name); Logger.log('birthdayAgeToCalendar.  . Name: ' + name); for (var c in contacts) { var bday = contacts[c].getDates(ContactsApp.Field.BIRTHDAY); var bdayMonthName, bdayYear, bdayDate; try { bdayMonthName = bday[0].getMonth(); bdayYear = bday[0].getYear(); bdayDate = new Date(bdayMonthName + ' ' + bday[0].getDay() + ', ' + bdayYear); Logger.log('birthdayAgeToCalendar. bdayDate: ' + bdayDate); } catch (error) {} var years = parseInt(new Date().getFullYear()) - bdayYear; try { defaultCal.createAllDayEvent(name + " –  , " + years + "  ()", new Date(bdayMonthName + ' ' + bday[0].getDay() + ', ' + new Date().getFullYear())); Logger.log(": " + name + " –  , " + years + "  ()"); } catch (error) {} } } } function anniversaryAgeToCalendar() { // for (var i in events) { Logger.log('anniversaryAgeToCalendar. . : ' + events[i].getTitle()); var name = events[i].getTitle().split("   ")[1]; var contacts = ContactsApp.getContactsByName(name); Logger.log('anniversaryAgeToCalendar. . Name: ' + name); for (var c in contacts) { var bday = contacts[c].getDates(ContactsApp.Field.ANNIVERSARY); //   https://developers.google.com/apps-script/reference/contacts/field var bdayMonthName, bdayYear, bdayDate; try { bdayMonthName = bday[0].getMonth(); bdayYear = bday[0].getYear(); bdayDate = new Date(bdayMonthName + ' ' + bday[0].getDay() + ', ' + bdayYear); Logger.log('anniversaryAgeToCalendar. bdayDate: ' + bdayDate); } catch (error) {} var years = parseInt(new Date().getFullYear()) - bdayYear; try { defaultCal.createAllDayEvent("   " + name + ", " + years + "  ()", new Date(bdayMonthName + ' ' + bday[0].getDay() + ', ' + new Date().getFullYear())); Logger.log(": " + "   " + name + ", " + years + "  ()"); } catch (error) {} } } } function TriggersCreateTimeDriven() { //      // Deletes all triggers in the current project. var triggers = ScriptApp.getProjectTriggers(); for (var i = 0; i < triggers.length; i++) { ScriptApp.deleteTrigger(triggers[i]); } //    ScriptApp.newTrigger("birthdayAgeToCalendar") //  .timeBased() .onMonthDay(1) //  .atHour(1) .create(); ScriptApp.newTrigger("anniversaryAgeToCalendar") // .timeBased() .onMonthDay(1) .atHour(2) .create(); } 

Como usar?


1.Crie um novo script do Google Apps no Google Drive:



2. Copie o código do script.


3. Teste a função "birthdayAgeToCalendar" - o script criará eventos no calendário padrão, indicando a idade das pessoas que terão aniversários dentro de 31 dias (mas este ano):



4.Ver Exibir / Logs:



5.Verifique o calendário:



6. Se tudo estiver em ordem, execute a função “TriggersCreateTimeDriven” - ele criará uma inicialização automática das funções “birthdayAgeToCalendar” e “anniversaryAgeToCalendar” para cada primeiro dia do mês com antecedência.


Sumário


Acredito que o problema de exibir idade no calendário do Google quando ocorrem eventos significativos foi resolvido. Também quero agradecer a Yevgeny Namokonov ( canal de telegrama “Google Sheets” ) e Alexander Ivanov, junto com seu canal de telegrama, pela ajuda na separação e edição do código escrito.


Mais detalhes podem ser encontrados no GitHub .


Publicado por: Mikhail Shardin ,
25 de dezembro de 2019

Source: https://habr.com/ru/post/pt481858/


All Articles