在Google表格上插入日期和时间

时间:2015-06-20 21:04:39

标签: date time google-sheets

在Google表格上; 我希望它显示日/月/年&小时/分钟

当我点击插入日期时,它显示6/20/2015 21:59:4

我希望它显示20/06/2015 21:59

我尝试了一些事情并且我设法改变了月/日,但是它引发了错误,所以不得不重新开始。

如果有人有更好的代码或者可以修复此代码,那将会有所帮助!

    function getDate() {
  var d = new Date();
  return (d.getMonth()+1) + "/" + d.getDate() + "/" + d.getFullYear();
}

function getTime() {
  var d = new Date(),
      offset = -d.getTimezoneOffset()/60,
      h = d.getUTCHours() + offset,
      m = d.getMinutes(),
      s = d.getSeconds();
  return h + ":" + m + ":" + s;
}

function getDateAndTime() {
  return getDate() + " " + getTime();
}

function insertValue(theValue, format) {
  var ss = SpreadsheetApp.getActiveSpreadsheet(),
      theSheet = ss.getActiveSheet(),
      theCell = theSheet.getActiveSelection();
  theCell.setNumberFormat(format || theCell.getNumberFormat());
  theCell.setValue(theValue);
  return true;
}

function getValue() {
  return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getActiveCell().getValue();
}

function getFormat() {
    return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getActiveCell().getNumberFormat();
}

function insertDate() {
  insertValue(getDate(), "Date");
}

function insertTime() {
  insertValue(getTime(), "Time");
}

function insertDateAndTime() {
  insertValue(getDateAndTime(), "Date time");
}

function appendDate() {
  insertValue(getValue() + " " + getDate());
}

function appendTime() {
  insertValue(getValue() + " " + getTime());
}

function appendDateAndTime() {
  insertValue(getValue() + " " + getDateAndTime());
}

function onOpen() {  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var menuEntries = [];
  menuEntries.push({name: "Insert Date", functionName: "insertDate"});
  menuEntries.push({name: "Insert Time", functionName: "insertTime"});
  menuEntries.push({name: "Insert Date and Time", functionName: "insertDateAndTime"});
  menuEntries.push(null); // line separator
  menuEntries.push({name: "Append Date", functionName: "appendDate"});
  menuEntries.push({name: "Append Time", functionName: "appendTime"});
  menuEntries.push({name: "Append Date and Time", functionName: "appendDateAndTime"});

  ss.addMenu("Insert Date", menuEntries);
}

function onInstall() { onOpen(); }

2 个答案:

答案 0 :(得分:0)

这个公式可以按你的意愿运作:

= TEXT(NOW(),“dd / mm / yyyy hh:mm”)

答案 1 :(得分:0)

也许使用Utilities.formatDate()。 见here for more info

示例:

var formattedDate = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd/MM/yyyy HH:mm");