Search code examples
google-apps-scriptgmail-addons

How to get the client's time in a gmail add-on?


I would like to know the timezone of the user who runs the gmail add-on.

Trying the following code did not comply to the client's time zone :

var formattedDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");
Logger.log(formattedDate);

I basically want to filter my response and just show the upcoming events to the user.


Solution

  • There's the official documented way to retrieve timezone info in Gmail add-ons. Add the following scope to your manifest file:

     "oauthScopes":["https://www.googleapis.com/auth/script.locale", ....]
    

    Set the 'gmail.userLocaleFromApp' property to 'true':

     "gmail": {"useLocaleFromApp": true}
    

    Set the "onTriggerFunction" property to whatever function you are using to start up the add-on. The code below displays the card showing timezone details for the user running the add-on.

    function loadAddon(e){
    
    var accessToken = e.messageMetadata.accessToken;
    GmailApp.setCurrentMessageAccessToken(accessToken);
    
    var userLocale = e.userLocale;
    var offset = e.userTimezone.offSet;
    var timezoneId = e.userTimezone.id;
    
    var message ="User locale: " + userLocale + 
                 "\nUTC offset: " + offset +  
                 " \nTimezone Id: " + timezoneId;
    
    var card = CardService.newCardBuilder()
                           .setHeader(CardService.newCardHeader()
                                          .setTitle("User timezone info"))
                           .addSection(CardService.newCardSection()
                                           .setHeader(Session.getActiveUser().getEmail())
                                           .addWidget(CardService.newTextParagraph()
                                           .setText(message)))
                           .build();
    
    return [card];
    
    }
    

    UPDATE There seems to be the error in the documentation that some of the editors pointed out:

    https://developers.google.com/gmail/add-ons/how-tos/access-user-locale

    The UTC offset is supposed to be e.userTimezone.offset, but is actually e.userTimezone.offSet.