diff --git a/core/src/components/datetime/datetime-util.ts b/core/src/components/datetime/datetime-util.ts index 865d6af6c2..c7a540e8e4 100644 --- a/core/src/components/datetime/datetime-util.ts +++ b/core/src/components/datetime/datetime-util.ts @@ -248,8 +248,20 @@ export function parseDate(val: string | undefined | null): DatetimeData | undefi * such as "01:47" */ export const getLocalDateTime = (dateString: any = ''): Date => { - const date = (typeof dateString === 'string' && dateString.length > 0) ? new Date(dateString) : new Date(); + /** + * Ensures that YYYY-MM-DD, YYYY-MM, + * YYYY-DD, etc does not get affected + * by timezones and stays on the day/month + * that the user provided + */ + if ( + dateString.length === 10 || + dateString.length === 7 + ) { + dateString += ' '; + } + const date = (typeof dateString === 'string' && dateString.length > 0) ? new Date(dateString) : new Date(); return new Date( Date.UTC( date.getFullYear(), @@ -267,7 +279,6 @@ export function updateDate(existingData: DatetimeData, newData: any): boolean { if (!newData || typeof newData === 'string') { const localDateTime = getLocalDateTime(newData); - if (!Number.isNaN(localDateTime.getTime())) { newData = localDateTime.toISOString(); } diff --git a/core/src/components/datetime/test/datetime.spec.ts b/core/src/components/datetime/test/datetime.spec.ts index 43f651bb3d..f099ae7ce4 100644 --- a/core/src/components/datetime/test/datetime.spec.ts +++ b/core/src/components/datetime/test/datetime.spec.ts @@ -52,6 +52,23 @@ describe('Datetime', () => { expect(convertToLocal.toISOString()).toEqual(expectedDateString); }); }); + + it('should format a date string and not get affected by the timezone offset', () => { + + const dateStringTests = [ + { input: '2019-03-20', expectedOutput: '2019-03-20' }, + { input: '1994-04-15', expectedOutput: '1994-04-15' }, + { input: '2008-09-02', expectedOutput: '2008-09-02' }, + { input: '1995-02', expectedOutput: '1995-02' }, + { input: '1994-03-14', expectedOutput: '1994-03-14' }, + { input: '9 01:47', expectedOutput: '09-01T01:47' } + ]; + + dateStringTests.forEach(test => { + const convertToLocal = getLocalDateTime(test.input); + expect(convertToLocal.toISOString()).toContain(test.expectedOutput); + }); + }); }); describe('daysInMonth()', () => {