Code Guy
Code Guy

Reputation: 3198

Local time vs Script time and Trigger time in Google apps script

The script time is set to GMT 00

The script accepts date and time from the user

The user sets local date time from the datetime field

The user clicks set button

This will create a trigger at GMT time, How do make it to trigger at local time?

function onOpen() {
    SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
        .createMenu('Custom Menu').addItem('Show sidebar', 'showSidebar').addToUi();
}

function showSidebar() {
    var html = HtmlService.createHtmlOutputFromFile('Sidebar').setTitle('My custom sidebar').setWidth(300);
    SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
        .showSidebar(html);
}

function sendEmail() {
    GmailApp.sendEmail(Session.getEffectiveUser().getEmail(), 'Reminder C Email', 'Reminding you about...');
}

function create(AT) {
    SpreadsheetApp.getUi().alert(AT)
    var at = moment(AT);
    ScriptApp.newTrigger('sendEmail').timeBased().at(new Date(at)).inTimezone(getDefaultUserTimeZone()).create();
}
//script timezone is GMT 00
function getDefaultUserTimeZone() {
    if (CalendarApp.getDefaultCalendar()) return CalendarApp.getDefaultCalendar().getTimeZone();
    else return 'Etc/GMT';
}

Upvotes: 2

Views: 555

Answers (1)

Alan Wells
Alan Wells

Reputation: 31300

If the only reason you are accessing the calendar, is to get the default time zone, then I would not do that. You can get the default user time zone from the spreadsheet.

ssTimeZone = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();

And since you are already using the spreadsheet, why not just use that?

function create(AT, l)
{
  var ssTimeZone;

  //SpreadsheetApp.getUi().alert(AT)
  var at = moment(AT);

  var offsetTime = new Date(new Date(at).getTime() + l * 60 * 1000);

  ssTimeZone = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();

  //showAlert(offsetTime)
  ScriptApp.newTrigger('sendEmail').timeBased()
    .at(new Date(offsetTime))
    .inTimezone(ssTimeZone)
    .create();

}

Upvotes: 1

Related Questions