Skip to content
Permalink
Browse files

fix(datetime): date strings no longer revert to previous day (#18018)

fixes #17977
  • Loading branch information...
liamdebeasi committed Apr 16, 2019
1 parent 4474974 commit cc60b60135f1868cecbcd9a914d67733c1dbec7f
Showing with 30 additions and 2 deletions.
  1. +13 −2 core/src/components/datetime/datetime-util.ts
  2. +17 −0 core/src/components/datetime/test/datetime.spec.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();
}
@@ -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()', () => {

0 comments on commit cc60b60

Please sign in to comment.
You can’t perform that action at this time.