hunter21188
hunter21188

Reputation: 415

Google Apps Script - Adding n Hours to Current Time and Date

I am new to the Google Apps Script code and am trying to simply add a user defined number of hours to the current time (lets say 12 hours for example). The code would then insert the time and date 12 hours into the future within a google doc.

I use a ui.prompt to have the user enter the number of hours into the future they want. The code I have does not give me an error, but it puts in the current hour some strange number of days into the future (not sure why it is doing this). This is the code I have and the else section is where I am running into issues...

function UpdateDocument() {

  var document = DocumentApp.getActiveDocument();
  var date = new Date();
  var tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate()+1);
  var ui = DocumentApp.getUi();

var regExpUpdateDate = "[A-Z]{3}, [A-Z]{3} [A-Z]{1}, [A-Z]{4}"; // Regular expression to find the correct line for the Next Update

  // Ask User if the they want to include the Next Update Line  
  var response = ui.alert('Would you like to include the Next Update line?' , ui.ButtonSet.YES_NO);

  // Process the users response.
  if (response == ui.Button.YES) {
    var responseNextUpdate = ui.prompt('Enter the number of hours you want until the next update (i.e. 12, 24, etc.)' 
                                       + ' or leave blank if you only want to include the date and omit the time. Note that'
                                       + ' leaving it blank will default to the day 24 hours from now.'); // Prompts user for number of hours until the next update
    if (responseNextUpdate.getResponseText() == '') {
      document.replaceText(regExpUpdateDate, Utilities.formatDate(tomorrow, 'America/Denver', 'EEEE, MMMM d, yyyy'));
    }
    else { // This is the section that I am having issues with...
      var userSelectedHours = new Date();
      userSelectedHours.setDate(userSelectedHours.getHours() + 2);
      document.replaceText(regExpUpdateDate, Utilities.formatDate(userSelectedHours, 'America/Denver', 'h a EEEE, MMMM d, yyyy'));
    }
  }
}

Upvotes: 2

Views: 13723

Answers (3)

Fabio TK
Fabio TK

Reputation: 11

I had the same problem, and got the data from the variables and combined in a new variable. Below I am copying the part of the code. It is not smooth, but it is working...

  // The commands in the next lines were required to combine date and time
  // event_values[7] corresponds to the date of the event provided by the form to the spreadsheet as dd/MM/yyyy
  var day = new Date(event_values[7].toLocaleString()).getDate().valueOf();
  var month=new Date(event_values[7].toLocaleString()).getMonth().valueOf();
  var year=new Date(event_values[7].toLocaleString()).getFullYear().valueOf();
  // event_values[8] and [9] correspond to the start and end time of the event as HH:mm:ss also provided by the form to the spreadsheet
  var start_time=event_values[8].toString().split(":");
  // since the day was not provided for the start_time and end_time variables, in my case the script assumed as 1899. So I split the string first with ":" and then with "1899 ".
  var start_hour=start_time[0].split("1899 ")[1].valueOf();
  var start_min=start_time[1].valueOf();
  var end_time=event_values[9].toString().split(":")
  var end_hour=end_time[0].split("1899 ")[1].valueOf();
  var end_min=end_time[1].valueOf();

  var event_start_time = new Date(year,month,day,start_hour,start_min,"00");
  var event_end_time=new Date(year,month,day,end_hour,end_min,"00");

Upvotes: 0

ADW
ADW

Reputation: 4247

I find it easier to use milliseconds to add/subtract time.

  var now = new Date(); // Fri Jul 05 09:53:12 GMT+05:30 2019

  var nowInMS = now.getTime(); // 1562300592245

  var add = 12 * 60 * 60 * 1000; // 43200000 = 12 hours in milliseconds

  var twelveHoursLater = nowInMS + add; // 1562343792245

  var futureDate = new Date(twelveHoursLater); // Fri Jul 05 21:53:12 GMT+05:30 2019

  var futureDateFormatted = Utilities.formatDate(futureDate, Session.getScriptTimeZone(), "dd-MMM-yy hh:mm a"); // 05-Jul-19 09:53 PM

Upvotes: 6

Cooper
Cooper

Reputation: 64062

Try this:

function UpdateDocument() {
  var document = DocumentApp.getActiveDocument();
  var date = new Date();
  var tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate()+1);
  var ui = DocumentApp.getUi();
  var regExpUpdateDate = "[A-Z]{3}, [A-Z]{3} [A-Z]{1}, [A-Z]{4}"; 
  var response = ui.alert('Would you like to include the Next Update line?' , ui.ButtonSet.YES_NO);
  if (response == ui.Button.YES) {
    var responseNextUpdate = ui.prompt('Enter the number of hours you want until the next update (i.e. 12, 24, etc.) or leave blank if you only want to include the date and omit the time. Note that leaving it blank will default to the day 24 hours from now.');
    if (responseNextUpdate.getResponseText() == '') {
      document.replaceText(regExpUpdateDate, Utilities.formatDate(tomorrow, 'America/Denver', 'EEEE, MMMM d, yyyy'));
    }
    else { // This is the section that I am having issues with...
      var hours=Number(responseNextUpdate.getResponseText());
      var delayedDate =new Date(new Date().setHours(new Date().getHours() + hours));
      document.replaceText(regExpUpdateDate, Utilities.formatDate(delayedDate, 'America/Denver', 'h a EEEE, MMMM d, yyyy'));
      Logger.log(Utilities.formatDate(delayedDate, 'America/Denver', 'h a EEEE, MMMM d, yyyy'));
    }
  }
}

Upvotes: 2

Related Questions