fix(DatePipe): handle empty string (#12374)

This commit is contained in:
Dzmitry Shylovich 2016-11-09 02:45:12 +03:00 committed by vikerman
parent 09092ac3c2
commit 3dc61779f0
2 changed files with 25 additions and 18 deletions

View File

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

View File

@ -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', () => {