Skip to content

Commit

Permalink
make parseDate more robust
Browse files Browse the repository at this point in the history
  • Loading branch information
mmalerba committed Feb 1, 2017
1 parent 251271c commit b7350de
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
19 changes: 17 additions & 2 deletions src/lib/core/datetime/calendar-locale.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,26 @@ describe('DefaultCalendarLocale', () => {
expect(calendarLocale.openCalendarLabel).toBe('Open calendar');
});

it('parses simple dates', () => {
it('parses SimpleDate from string', () => {
expect(calendarLocale.parseDate('1/1/2017')).toEqual(new SimpleDate(2017, 0, 1));
});

it('formats simple dates', () => {
it('parses SimpleDate from number', () => {
let timestamp = new Date().getTime();
expect(calendarLocale.parseDate(timestamp))
.toEqual(SimpleDate.fromNativeDate(new Date(timestamp)));
});

it ('parses SimpleDate from SimpleDate by copying', () => {
let originalSimpleDate = new SimpleDate(2017, 0, 1);
expect(calendarLocale.parseDate(originalSimpleDate)).toEqual(originalSimpleDate);
});

it('parses null for invalid dates', () => {
expect(calendarLocale.parseDate('hello')).toBeNull();
});

it('formats SimpleDates', () => {
expect(calendarLocale.formatDate(new SimpleDate(2017, 0, 1))).toEqual('1/1/2017');
});

Expand Down
16 changes: 11 additions & 5 deletions src/lib/core/datetime/calendar-locale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import {SimpleDate} from './simple-date';
import {Injectable} from '@angular/core';


/** Whether the browser supports the Intl API. */
const SUPPORTS_INTL_API = !!Intl;


/** Creates an array and fills it with values. */
function range<T>(length: number, valueFunction: (index: number) => T): T[] {
return Array.apply(null, Array(length)).map((v: undefined, i: number) => valueFunction(i));
}
Expand Down Expand Up @@ -51,10 +53,10 @@ export abstract class CalendarLocale {
openCalendarLabel: string;

/**
* Parses a SimpleDate from a string.
* @param dateString The string to parse.
* Parses a SimpleDate from a value.
* @param value The value to parse.
*/
parseDate: (dateString: string) => SimpleDate;
parseDate: (value: any) => SimpleDate;

/**
* Formats a SimpleDate to a string.
Expand Down Expand Up @@ -122,8 +124,12 @@ export class DefaultCalendarLocale implements CalendarLocale {

openCalendarLabel = 'Open calendar';

parseDate(dateString: string) {
return SimpleDate.fromNativeDate(new Date(Date.parse(dateString)));
parseDate(value: any) {
if (value instanceof SimpleDate) {
return value;
}
let timestamp = typeof value == 'number' ? value : Date.parse(value);
return isNaN(timestamp) ? null : SimpleDate.fromNativeDate(new Date(timestamp));
}

formatDate = this._createFormatFunction(
Expand Down

0 comments on commit b7350de

Please sign in to comment.