2

本质上,我希望在将新电子表格创建为纯文本时将 YYYY-MM-DD 格式插入到新电子表格的单元格中。问题在于,当插入的值插入新工作表时,它显示为 DD/MM/YYYY,后台运行的其他程序无法读取。

这是以下代码:

function dateTest() 
{
var template = SpreadsheetApp.openById('ABC------1234')
var test = template.getSheetByName('TEST');
var database = SpreadsheetApp.getActive().getSheetByName('DASHBOARD');

//start & endDates are in YYYY-MM-DD format in these cells
var startDate = database.getRange('A10').getValue();
var endDate = database.getRange('A11').getValue();

//The results come up as DD/MM/YYYY when they are set into TEST
//Formatted to YYYY-MM-DD has already been done 
test.getRange('D1').setValue(startDate);
test.getRange('D2').setValue(endDate);

}

如有必要,可以将日期拆分为 YYYY + '-' + 'MM' + '-' + 'DD' 然后作为纯文本插入,但是我不知道如何执行此壮举。任何建议将不胜感激。

4

4 回答 4

4

它可以清理,但这里是基础知识。

//start & endDates are in YYYY-MM-DD format in these cells
var startDate = database.getRange('A10').getValue();
var strStartDate = startDate.getFullYear() + "-" + (startDate.getMonth() + 1) + "-" + startDate.getDate();
var endDate = database.getRange('A11').getValue();
var strEndDate = endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + endDate.getDate();

//The results come up as DD/MM/YYYY when they are set into TEST
//Formatted to YYYY-MM-DD has already been done 
test.getRange('D1').setNumberFormat('@STRING@');
test.getRange('D1').setValue(strStartDate);

test.getRange('D2').setNumberFormat('@STRING@');
test.getRange('D2').setValue(strEndDate);
于 2012-12-31T20:12:53.803 回答
3

在 Google 电子表格中,前导撇号表示忽略格式。因此,这有效:

range.setValue("'2007-09-12");

或者,文本可以被引用并设置为“公式”:

range.setFormula('"2007-09-12"');

(确保字符串包含双引号而不是单引号 - Apps 脚本是 JavaScript,因此两者都支持,但电子表格公式不能以同样的方式理解单引号。)

于 2012-12-31T20:43:50.837 回答
0

这将重新格式化日期并将其设置为字符串:

  var tz = ss.getSpreadsheetTimeZone();
  var newDate = Utilities.formatDate(startDate, tz, 'yyyy-MM-dd'); // Requested format
  s.getRange('D1').setValue("'" + newDate);  // Set as string
于 2012-12-31T16:04:23.237 回答
0

尝试此解决方法:在工作表中手动将单元格格式设置为不参与操作的“纯文本”。我们称这个单元格为 J1。现在在调用之前:

test.getRange('D1').setValue(startDate);
test.getRange('D2').setValue(endDate);

执行以下操作:

test.getRange('J1').copyFormatToRange(test,3,3,0,1); // This is D1 and D2
test.getRange('D1').setValue(startDate);
test.getRange('D2').setValue(endDate);

这应该让您在目标单元格上有清晰的文本格式。

于 2012-12-31T14:43:38.083 回答