首页 > 解决方案 > 如何更改图表中的时间格式?

问题描述

如何删除图表中秒的显示?我有一个图表,其中时间以格式显示hh.mm.ss

这是如何绘制图表的完整代码。

ts:

 @ViewChild('state') stateRef: ElementRef

  ngAfterViewInit() {

    const densityConfig: any = {
      label: 'Density',
      backgroundColor: 'rgba(0, 150, 136, .2)',
      borderColor: 'rgba(0, 121, 107, .7)',
      borderWidth: 2
    }

    const visconsityConfig: any = {
      label: 'Visconsity',
      backgroundColor: 'rgba(0, 137, 132, .2)',
      borderColor: 'rgba(0, 10, 130, .7)',
      borderWidth: 2
    }

    const stateTimeConfig: any = {
      datasets: [ visconsityConfig, densityConfig]
    }

    this.stateService.fetch().subscribe((data: State[]) => {
      densityConfig.data = data.map(item => item.density)
      visconsityConfig.data = data.map(item => item.visconsity)
      stateTimeConfig.labels = data.map(item => item.state_time)
      const stateCtx = this.stateRef.nativeElement.getContext('2d')

      new Chart(stateCtx, {
        type: 'line',
        data: stateTimeConfig,
        options: {
          responsive: true
        }
      })
    })
  }

html:

<div *ngIf="states">
  <canvas  #state></canvas>
</div>

state_time负责时间。

标签: angular

解决方案


您将使用来自 Angular 的内置日期管道:

我创建了一个简短的StackBlitz 来查看它

为简洁起见,做了一些小改动,但您可以在这里看到重要的部分:

ts 文件只是一个日期数组:

  labels: Date[] = [new Date('2018/10,5 01:15:31'), 
     new Date('2017/2/25 01:15:10'), new Date('2001/1/1 12:10:01')];
  }

html文件是:

<div *ngFor="let date of labels">
  Short Time: {{date | date:'shortTime'}} 
  hhmm: {{date | date:'HH:mm'}} 
</div>

有关日期管道可用格式的更多信息


更新

看到这是 Angularjs,或者至少在后端,我认为你最好的选择是使用 Javascript:

stateTimeConfig.labels = data.map(item => item.state_time.toLocaleTimeString([],
     {hour: '2-digit', minute:'2-digit', hour12:false}))

小时是 HH,为 2 位数。分钟和 12 小时对于我们这些使用奇怪的 12 小时系统的人来说,它会显示 12:15 而不是 12:15 AM/PM。如果您想要上午/下午,那么只需将该选项排除在外。


推荐阅读