angular - 如何将 Angular 5 中的时间从 24 小时格式更改为 12 小时格式

标签 angular angular5 angular-pipe

我在我的应用程序中使用了输入类型 time 来接收时间:

  <mat-input-container>
<input matInput  formControlName="start_time" type="time" placeholder="Time Start">
<p class="invalid-text" *ngIf="dvrForm.controls.start_time.invalid &&
        (dvrForm.controls.start_time.dirty || dvrForm.controls.start_time.touched)">
  <span *ngIf="dvrForm.controls.start_time.errors.required"> Start Time is required.</span></p>

在我通过输入存储数据后,它以 24 小时格式存储:

View Of database how the time is stored

所以现在当我在我的 View 中显示它时,它以相同的格式显示,例如:23:11:00,是否可以使用管道之类的东西将其转换为 12 小时格式,同时在 View 中显示。

最佳答案

是的,你可以通过管道来完成:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'convertFrom24To12Format'})
export class TimeFormat implements PipeTransform {
     transform(time: any): any {
         let hour = (time.split(':'))[0]
         let min = (time.split(':'))[1]
         let part = hour > 12 ? 'pm' : 'am';
         if(parseInt(hour) == 0)
          hour = 12;
         min = (min+'').length == 1 ? `0${min}` : min;
         hour = hour > 12 ? hour - 12 : hour;
         hour = (hour+'').length == 1 ? `0${hour}` : hour;
         return `${hour}:${min} ${part}`
       }
   }

例如在您的 html 中:

<p>Time Format From  24 to 12 : {{'23:11:00' | convertFrom24To12Format}}</p>

希望对您有所帮助!!

关于angular - 如何将 Angular 5 中的时间从 24 小时格式更改为 12 小时格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50362854/

相关文章:

angular - 对 Electron 使用 Angular 路由

json - 使用带有 http 和 observables 的 angular2 在 json 文件中添加/更新/删除产品

angular - Angular 7 和 8 有什么区别?

datatables - 在Angular 5数据表: cannot reinitialise DataTable中遇到错误

typescript - 如何使用可变参数重载函数

Angular - 找不到名称的管道

angular - moment().add() 仅适用于文字值

javascript - rxjs 中的 flatMap、mergeMap、switchMap 和 concatMap?

angular5 - 如何设置 PrimeNG p-dropdown 的默认值

angular - Typescript 将时间戳转换为 mm-dd 格式