【问题标题】:Formatting time in JSON to display in ag-grid以 JSON 格式格式化时间以在 ag-grid 中显示
【发布时间】:2018-10-09 02:53:14
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: json angular typescript ionic-framework ag-grid


    【解决方案1】:

    也许你会在这个 Pipe 中创建一个 Pipe 和 mommentjs。

    【讨论】:

    • 根据我的经验,Angular 的日期管道可以完成人们使用 moment.js 的大部分工作。我建议在集成其他框架之前尝试直接使用 DatePipe 或作为 CustomDatePipe 中的注入服务。
    • 非常棒,我已经给别人了
    【解决方案2】:

    在 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)。

    当 AgGrid 尝试渲染它时,管道的 transform() 方法将格式化您想要显示的 JSON 部分(在您的情况下为日期属性)。

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

    &lt;div class="my-awesome-date-style"&gt;${params.date | customDatePipe}&lt;/div&gt;

    【讨论】:

    • 这可能可行,但是由于您的回答,我偶然发现了这个文档ag-grid.com/javascript-grid-cell-rendering,上面写着“如果您只想对数据进行简单的格式化(例如货币或日期格式),那么您可以使用 colDef.valueFormatter",所以我决定使用 valueFormatter。
    【解决方案3】:

    我没有找到一个相同的问题,它很简单,所以我将解释我做了什么:

    在 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 每次都采用相同格式时才有效。

    【讨论】:

      【解决方案4】:

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

      在您的 .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 库,您可以配置多种日期格式,包括语言环境支持。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-04
        • 1970-01-01
        • 2022-01-04
        • 2013-08-19
        • 2016-02-10
        • 2021-04-24
        • 1970-01-01
        • 2020-06-12
        相关资源
        最近更新 更多