将字符串转换为日期问题

时间:2016-11-02 14:16:27

标签: angular typescript

我想为angular2创建一个管道,这就是代码:

@Pipe({name: 'stringToDate'})
export class StringToDatePipe implements PipeTransform {
    /**
     * Constructor
     */
    constructor() {
    }
    /**
     * Transform a date that is passed as string into a date
     * @param value The date passed as string
     * @returns {Date} The Date object
     */
    transform(value: string): Date {
        console.log(value);
        let d = new Date(value);
        console.log(d);
        return d;
    }
}

我不知道为什么没有创建正确的日期。这是控制台打印的内容:

2016-01-01
Thu Dec 31 2015 21:00:00 GMT-0300

我该如何解决?

1 个答案:

答案 0 :(得分:3)

可能的解决方案:

@Pipe({name: 'stringToDate'})
export class StringToDatePipe implements PipeTransform {
    /**
     * Constructor
     */
    constructor() {
    }
    /**
     * Transform a date that is passed as string into a date
     * @param value The date passed as string
     * @returns {Date} The Date object
     */
    transform(value: string): Date {
        let reggie = /(\d{4})-(\d{2})-(\d{2})/;
        let dateArray = reggie.exec(value);
        let dateObject = new Date(
            (+dateArray[1]),
            ((+dateArray[2])) - 1, // Careful, month starts at 0!
            (+dateArray[3])
        );
        return dateObject;
    }
}