【问题标题】:Time converting pipe for angular角度时间转换管道
【发布时间】:2020-01-10 06:11:28
【问题描述】:

当我使用角度对象渲染时间戳时,我希望将时间戳转换为 HTML 我有一个对象,我的开始和结束时间为 09:15:00 和 13:20:45 我想使用 html 中的管道将它们转换为上午 9:15 和下午 13:20

<div>{{start_time}} {{end_time}}</div>

09:15:00 13:20:45

我如何使用角管道来实现这一点,因为我不能在这里使用日期管道,因为只有当我们在对象中有日期时才有效 我如何使用角管道来实现这一点,因为我不能在这里使用日期管道,因为只有当我们在对象中有日期时才有效

谁能帮忙...

【问题讨论】:

    标签: javascript angular6


    【解决方案1】:
    import * as moment from 'moment';
    
    @Pipe({
      name: 'customTimePipe'
    })
    export class CustomTimePipe implements PipeTransform {
      transform(value: any, args?: any): any {
        return moment(value,'HH:mm').format("HH:mm A");
      }
    }
    

    这是管道文件

    以后你必须在 HTML 中这样使用

    <div>{{start_time | customTimePipe}} {{end_time | customTimePipe}}</div>
    

    希望这能解决你的问题。

    【讨论】:

    • 这里你已经静态定义了09:00:00,这怎么能像当前时间的访问者开始时间和结束时间一样是动态的?
    【解决方案2】:

    您可以创建自定义“时间转换”pipe

    import { Pipe, PipeTransform } from '@angular/core';
    import moment = require('moment');
    @Pipe({name: 'datepipe'})
    export class datepipe implements PipeTransform{
    
        transform(value:any, args:any){
    
            return moment(value,'HH:mm').format("HH:mm A");
    
        }
    
    }
    

    并在显示时使用此管道。

    {{start_time | datepipe}}  {{end_time | datepipe}}
    

    DEMO

    【讨论】:

      【解决方案3】:

      您可以尝试将时间戳转换为日期吗

      new Date(timestamp)
      

      然后尝试使用数据管道

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 2017-10-18
        • 2021-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多