格式化 JSON 中的时间以显示在 ag-grid 中

Formatting time in JSON to display in ag-grid

我正在使用带有 angular 5 的 ag-grid。 我的目标是有一个包含一些列的网格,其中一列是 "Time" 列,并以这种格式显示时间“hh:mm”。

我在网格中显示的所有数据都来自 JSON 对象。现在我显示的时间看起来像这样“2018-04-28T08:16:07.632Z”。

我看过一些 Angular 管道,但我不知道如何将它用于需要格式化一列的 JSON 对象,但它必须是 "bound" 到其他列中的正确单元格。我认为所有的格式都必须在打字稿代码中完成。

你们有没有人做过类似的事情或者有想法必须这样做?

也许您会创建一个 Pipe 并在此 Pipe 中创建 mommentjs。

在 Ag-Grid 中,您可以在某些时候定义网格选项:

this.gridOptions = {
  // ...
  columnDefs: [    'DATE': {
     headerName: 'Datum',
     field: 'myJson.date',
     cellRenderer: (params: ICellRendererParams) => params.value ? 
        `<div class="my-awesome-date-style">${this._customDatePipe.transform(params.value)}</div>` : ''
  }],
  // ...
}

要在打字稿文件中(例如模板外部)使用管道(无论是您自己的 CustomDatePipe 还是 Angular 的原生 DatePipe),您必须注入它:

constructor(private readonly _customDatePipe: CustomDatePipe) {}

并在您的模块提供程序中包含 CustomDatePipe(或原生 DatePipe 的 CommonModule)。

管道的 transform() 方法将格式化 JSON 的部分(在您的例子中是日期-属性),您希望在 AgGrid 尝试渲染它时立即显示它。

PS:如果您使用的是 AgGrid CellRenderer-Component,您可以直接在其模板中使用管道而无需注入(尽管仍需要放入提供程序):

<div class="my-awesome-date-style">${params.date | customDatePipe}</div>

我还没有找到与此相同的问题,它非常简单,所以我将解释我所做的事情:

我在 coulmDefs 中添加了 valueFormatter: HomePage.timeFormatter

columnDefs = [
    {headerName: 'Time', field: 'time', valueFormatter: HomePage.timeFormatter}]

然后我将这个函数添加到同一个文件中:

// I take the substring of this '2018-04-28T08:16:07.632Z' and I get '08:16'
static timeFormatter(params) {return params.value.substring(11, 16);}

请记住,这仅在您知道 DateTime 每次都采用相同格式时才有效。

这是针对 Angular2+ 版本的。如果您在应用程序中使用 moment 库。那么这个工作真的很简单

在您的 .ts 文件中:

    import * as moment from 'moment';

{
    headerName: 'End Date',
    field: 'endDateUTC',
    minWidth: 80,
    maxWidth: 100,
    valueFormatter: function (params) {
        return moment(params.value).format('hh:mm');
    },
},

你将得到的输出是:

结束日期: 10:55

使用 moment 库,您可以配置多种日期格式,包括语言环境支持。

希望这对某些人有所帮助。