1

I want to create a pipe for angular2, and this is the code:

@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;
    }
}

I don't know why it is not creating the correct date. This is what console prints:

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

How can I fix it?

FacundoGFlores
  • 7,858
  • 12
  • 64
  • 94
  • The date object is not the same as the date string – FacundoGFlores Nov 02 '16 at 14:34
  • Looks like a dup of http://stackoverflow.com/questions/17545708/parse-date-without-timezone-javascript – Günter Zöchbauer Nov 02 '16 at 14:36
  • What happens is, you get a date as a `yyyy-mm-dd` string, and the `new Date(value)` converts the date string to a `Date` object. Then when the `Date` object is logged to the console, it is _formatted_ in the current time zone. Since the original string did not specify a time zone, the `Date()` function assumed GMT. So the Date object contains a 2016-01-01 GMT time, and displays it as a GMT-03 time -- is that the time zone of your PC? – Roy Dictus Nov 02 '16 at 14:39
  • Yes it is my PC's time zone. Look at my answer, is it a good approach? – FacundoGFlores Nov 02 '16 at 15:20

1 Answers1

3

A possible solution:

@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;
    }
}
FacundoGFlores
  • 7,858
  • 12
  • 64
  • 94