From 3dc61779f006959ef555999453d6983d647ebfcc Mon Sep 17 00:00:00 2001 From: Dzmitry Shylovich Date: Wed, 9 Nov 2016 02:45:12 +0300 Subject: [PATCH] fix(DatePipe): handle empty string (#12374) --- .../@angular/common/src/pipes/date_pipe.ts | 33 +++++++++++-------- .../common/test/pipes/date_pipe_spec.ts | 10 +++--- 2 files changed, 25 insertions(+), 18 deletions(-) diff --git a/modules/@angular/common/src/pipes/date_pipe.ts b/modules/@angular/common/src/pipes/date_pipe.ts index ba05c354e9..5315441e46 100644 --- a/modules/@angular/common/src/pipes/date_pipe.ts +++ b/modules/@angular/common/src/pipes/date_pipe.ts @@ -8,7 +8,7 @@ import {Inject, LOCALE_ID, Pipe, PipeTransform} from '@angular/core'; import {DateFormatter} from '../facade/intl'; -import {NumberWrapper, isBlank, isDate} from '../facade/lang'; +import {NumberWrapper, isDate} from '../facade/lang'; import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; @@ -97,20 +97,27 @@ export class DatePipe implements PipeTransform { transform(value: any, pattern: string = 'mediumDate'): string { if (isBlank(value)) return null; - if (!this.supports(value)) { + if (typeof value === 'string') { + value = value.trim(); + } + + let date: Date; + if (isDate(value)) { + date = value; + } else if (NumberWrapper.isNumeric(value)) { + date = new Date(parseFloat(value)); + } else { + date = new Date(value); + } + + if (!isDate(date)) { throw new InvalidPipeArgumentError(DatePipe, value); } - if (NumberWrapper.isNumeric(value)) { - value = parseFloat(value); - } - - return DateFormatter.format( - new Date(value), this._locale, DatePipe._ALIASES[pattern] || pattern); - } - - private supports(obj: any): boolean { - return isDate(obj) || NumberWrapper.isNumeric(obj) || - (typeof obj === 'string' && isDate(new Date(obj))); + return DateFormatter.format(date, this._locale, DatePipe._ALIASES[pattern] || pattern); } } + +function isBlank(obj: any): boolean { + return obj == null || obj === ''; +} diff --git a/modules/@angular/common/test/pipes/date_pipe_spec.ts b/modules/@angular/common/test/pipes/date_pipe_spec.ts index 62640fd639..0bd7f7a5d9 100644 --- a/modules/@angular/common/test/pipes/date_pipe_spec.ts +++ b/modules/@angular/common/test/pipes/date_pipe_spec.ts @@ -43,12 +43,12 @@ export function main() { () => { expect(() => pipe.transform('123456789.11')).not.toThrow(); }); it('should support ISO string', - () => { expect(() => pipe.transform('2015-06-15T21:43:11Z')).not.toThrow(); }); + () => expect(() => pipe.transform('2015-06-15T21:43:11Z')).not.toThrow()); - it('should not support other objects', () => { - expect(() => pipe.transform({})).toThrow(); - expect(() => pipe.transform('')).toThrow(); - }); + it('should return null for empty string', () => expect(pipe.transform('')).toEqual(null)); + + it('should not support other objects', + () => { expect(() => pipe.transform({})).toThrowError(); }); }); describe('transform', () => {