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?

4
  • The date object is not the same as the date string Commented Nov 2, 2016 at 14:34
  • Looks like a dup of stackoverflow.com/questions/17545708/… Commented Nov 2, 2016 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? Commented Nov 2, 2016 at 14:39
  • Yes it is my PC's time zone. Look at my answer, is it a good approach? Commented Nov 2, 2016 at 15:20

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.