0

If you run the codes below and your spreadsheet has a date column, the date format looks like this on the client page: Thu May 23 2013 00:00:00 GMT-0400 (EDT)

I want to format the date to something like this: May 23, 2013

I figure you could do that by changing the line

<td><?= data[i][j] ?></td>

to

<td><?= Utilities.formatDate(new Date(data[i][j]), "GMT-5", "MMM dd, yyyy")data[i][j] ?></td>

...but the problem is that not every data in the array is a date object. How do I check if an object in an array is of a certain type? I would like to determine if the current object is a date object before applying the formatDate function.

Code.gs

function doGet() {
  return HtmlService
      .createTemplateFromFile('index')
      .evaluate();
}

function getData() {
  return SpreadsheetApp
      .openById('123abc')
      .getDataRange()
      .getValues();
}

index.html

<? var data = getData(); ?>
<table>
  <? for (var i = 0; i < data.length; i++) { ?>
    <tr>
      <? for (var j = 0; j < data[i].length; j++) { ?>
        <td><?= data[i][j] ?></td>
      <? } ?>
    </tr>
  <? } ?>
</table>
4

1 回答 1

1

这里有很多关于在 javascript 中获取对象类型的问题和答案。确保您阅读了所有内容!

这是一个与现有代码样式相匹配的简单更改。将格式化程序函数放入 中Code.gs,并让模板化的 html 在构建表格时在每个“单元格”上使用它。

代码.gs

...你拥有的一切加上这个:

function formatIfDate(obj) {
  if (obj.constructor.name == 'Date')
    return Utilities.formatDate(new Date(obj), "GMT-5", "MMM dd, yyyy")
  else 
    return obj
};

索引.html

改变

<td><?= data[i][j] ?></td>

<td><?= formatIfDate(data[i][j]) ?></td>
于 2013-05-23T20:30:16.637 回答