Google Apps 脚本 - 将 n 小时添加到当前时间和日期

hun*_*188 1 google-apps-script

我是 Google Apps 脚本代码的新手,我正在尝试简单地将用户定义的小时数添加到当前时间(例如 12 小时)。然后,代码将在 Google 文档中插入未来 12 小时的时间和日期。

我使用 ui.prompt 让用户输入他们想要的未来的小时数。我的代码不会给我一个错误,但它会将当前时间放入未来的一些奇怪的天数中(不知道为什么要这样做)。这是我拥有的代码,该else部分是我遇到问题的地方......

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'));
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

ADW*_*ADW 5

我发现使用毫秒来添加/减去时间更容易。

  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
Run Code Online (Sandbox Code Playgroud)