DateTime error 21-undefined-2014 [duplicate]

2019-08-03 23:32发布

问题:

This question already has an answer here:

  • DateTime formatting 3 letter month 2 answers

The code below results in: 21-undefined-2014 Not sure what is missing. Please check and advise. Everything else seems to be working correctly. Thank you.

function onOpen() {
  var ui = DocumentApp.getUi();
  // Or FormApp or SpreadsheetApp.
  ui.createMenu('Custom Menu')
      .addItem('Insert Date', 'insertDate')
      .addToUi();

}

function insertDate() {
      var cursor = DocumentApp.getActiveDocument().getCursor();
      if (cursor) {
          // Attempt to insert text at the cursor position. If insertion returns null,
          // then the cursor's containing element doesn't allow text insertions.
          var month=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
          var d = new Date();
          var dd = d.getDate();
          dd = pad(dd, 2)
          var mm = d.getMonth();
          mm = pad(mm, 2)
          var yyyy = d.getFullYear();
          var date = dd + "-" + month[mm] + "-" + yyyy;
          var element = cursor.insertText(date);
          if (element) {
            element.setBold(true);
          } else {
            DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
          }
        } else {
          DocumentApp.getUi().alert('Cannot find a cursor in the document.');
      }

    }
function pad (str, max) {
  str = str.toString();
  return str.length < max ? pad("0" + str, max) : str;
}

回答1:

You shouldn't be doing

 mm = pad(mm, 2)

Check out this to confirm http://jsfiddle.net/baljeetsingh/JMs7t/2/