【问题标题】:Angular2 Date filter C# Date?Angular2日期过滤器C#日期?
【发布时间】:2016-06-22 14:56:15
【问题描述】:

是否有内置的日期管道过滤器以默认 asp.net JSON 序列化程序序列化日期的方式处理日期?

示例格式如下:'/Date(1466624402557)/'

否则我可以编写自定义管道。

每个 rinukkusu 这里是我创建的自定义管道:

import {PipeTransform, Pipe} from '@angular/core';
import {SlicePipe, DatePipe} from '@angular/common';

@Pipe({
    name: 'aspDate'
})
export class AspDatePipe implements PipeTransform {
    transform(value: string, arg: string): any {
        let slicedValue = new SlicePipe().transform(value, 6, -2);
        return new DatePipe().transform(slicedValue, arg );
    }
}

但是我得到了这个错误:

platform-b​​rowser.umd.js:962 原始异常:管道“DatePipe”的参数“1466624402557”无效

我已经尝试将切片字符串装箱到一个新的 Date() 但这也不起作用...

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以利用内置管道 slicedate 来实现此目的:

    {{ '/Date(1466624402557)/' | slice:6:-2 | date }}
    

    否则,请使用自定义管道路线。您可以像 date 管道参数一样使用它:

    @Pipe({
        name: 'aspDate'
    })
    export class AspDatePipe implements PipeTransform {
        transform(value: string, arg: string):any {
            let slicedValue = new SlicePipe().transform(value, 6, -2);
            return new DatePipe().transform(new Date(parseInt(slicedValue)), arg);
        }
    }
    

    例如在您的模板中:

    {{ '/Date(1466624402557)/' | aspDate:'fullDate' }}
    

    Plunker 用法示例

    【讨论】:

    • 感谢您展示这种在代码中链接管道过滤器的方法,我不会想到这一点。我收到了这个错误:platform-b​​rowser.umd.js:962 ORIGINAL EXCEPTION: Invalid argument '1466624402557' for pipe 'DatePipe'
    • 您使用的是哪个 Angular 2 版本?
    • 好的,我可以用 RC.1 重现它——不过,这个错误在 RC.3 中消失了!
    • 显然在 RC.1 中 DatePipe 只接受 Date 对象,没有时间戳字符串/数字格式。我编辑了答案并添加了new Date(parseInt(slicedValue))
    • 好的,我在实例化 js 日期时缺少解析 int 部分。这就是为什么我尝试装箱失败的原因。谢谢...
    【解决方案2】:

    这里是DatePipe,你可以直接查看它支持与否。目前不支持该格式:

    https://github.com/angular/angular/blob/5c8d3154d755f879d328739b78952fc88d38681f/modules/%40angular/common/src/pipes/date_pipe.ts

    【讨论】:

      【解决方案3】:

      据我所知,没有。你可以参考API of the date pipe in Angular,所以你必须自己实现它


      更新:

      根据Changelog添加的features的数字日期之一是“datePipe:数字字符串支持”你可以看到related commit here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-30
        • 2014-10-20
        • 2013-04-17
        • 1970-01-01
        • 1970-01-01
        • 2014-01-06
        • 1970-01-01
        • 2017-10-17
        相关资源
        最近更新 更多